Consider this base64 encode image
<img src='data:image/Png;base64,iVBORw0KGgoAAAANSUhEUgAAAFAAAABICAYAAABhlHJbAAAABHNCSVQICAgIfAhkiAAAAAFzUkdCAK7OHOkAAAAEZ0FNQQAAsY8L/GEFAAAACXBIWXMAABVlAAAVZQGF3cVdAAAAGXRFWHRTb2Z0d2FyZQB3d3cuaW5rc2NhcGUub3Jnm+48GgAABnNJREFUeF7tnFls3EQYx11ucQshClWbtb1LC4RLIARIHAXxgsQDCOWhJGs7mypIoII4BAIhsYAEWY+TlEo8FAQSQjxAuR54AnFUFHH0CQlEEWcaQhpKmx5poVWb8H3eb92Jd7Nre8a7a2d/0l9txvN99vw1HnvtGSsdqskYzu2ayb4A7dNN9oNm2E8qPW8fT5s71EOznDwYdxQ0x0s12LtXD248kaoFpFg8TisMX6Gb9t264dwHSR5PtEz7Mc10BrE92b6RnKLMLaGWulDPO+w3ryLoje8FMlG37As1094IQX/7k6RJqsl+wdNz2WDxVDXProWyGX8dv+qamFu34WQwbz1UPOIPTLec3+HfndXltQU9+P0qE1Vr9GzY+K2/MugACAfUd8q9Mslir4M+BMO+oXb52xpYaOLq1cUTyLziKVCIJvGVtmYMdlf4gTMZ4NkGpjq+NoeTwZ51k8EA+zS/AcaG5z13U0o2zy6FtoqO8ZNKpm/0AvgP350Z7SO1kHlTXJujalqB3vZApQCvSti1aT+pJGcOdUNbZZiHegtP308qBXCJfoL2k0q6+p1LYNzbwRkgoumca />
I would like to post this src to Mvc controller but getting null when post with ajax here is the post method.
var file = document.getElementById("base64image").src;
var formdata = new FormData();
formdata.append("base64image", file);
$.ajax({
url: "http://localhost:26792/home/SaveImage",
type: "POST",
data: file
});
Mvc Controller
[HttpPost]
public void SaveImage(Image file)
{
}
I think the datatype I am using is not valid for this please suggest me what can I do here.
Full Html Code
<!doctype html>
<html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>WebcamJS Test Page</title>
<style type="text/css">
body { font-family: Helvetica, sans-serif; }
h2, h3 { margin-top:0; }
form { margin-top: 15px; }
form > input { margin-right: 15px; }
#results { float:right; margin:20px; padding:20px; border:1px solid; background:#ccc; }
</style>
</head>
<body>
<div id="results">Your captured image will appear here...</div>
<h1>WebcamJS Test Page</h1>
<h3>Demonstrates simple 320x240 capture & display</h3>
<div id="my_camera"></div>
<!-- First, include the Webcam.js JavaScript Library -->
<script type="text/javascript" src="../webcam.min.js"></script>
<!-- Configure a few settings and attach camera -->
<script language="JavaScript">
Webcam.set({
width: 320,
height: 240,
image_format: 'jpeg',
jpeg_quality: 90
});
Webcam.attach( '#my_camera' );
</script>
<!-- A button for taking snaps -->
<form>
<input type=button id="takeshot" value="Take Snapshot" onClick="take_snapshot()">
</form>
<!-- Code to handle taking the snapshot and displaying it locally -->
<script language="JavaScript">
window.onload = function () {
setInterval(function () { take_snapshot() }, 5000);
}
function take_snapshot() {
// take snapshot and get image data
Webcam.snap( function(data_uri) {
// display results in page
document.getElementById('results').innerHTML =
'<h2>Here is your image:</h2>' +
'<img id="base64image" src="' + data_uri + '"/>';
});
var file = document.getElementById("base64image").src;
var formdata = new FormData();
formdata.append("base64image", file);
$.ajax({
url: "http://localhost:26792/home/SaveImage",
type: "POST",
data: file
});
//var ajax = new XMLHttpRequest();
//ajax.addEventListener("load", function (event) { uploadcomplete(event); }, false);
//ajax.open("POST", "http://localhost:26792/home/SaveImage");
//ajax.send(formdata);
}
</script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
</body>
</html>
I am not 100 % sure what your end goals are here. But the below answer explains how you can send a base64 image source string to server and save it. I tested it with a base64 string generated from a small image (22 KB size) and it worked.
In your ajax call, you should be sending the FormData object you created, not the value of file variable. Also make sure you use processData and contentType properties when making the ajax call while sending a FormData object.
var file = document.getElementById("base64image").src;
var formdata = new FormData();
formdata.append("base64image", file);
$.ajax({
url: "#Url.Action("SaveImage")",
type: "POST",
data: formdata,
processData: false,
contentType: false
});
Now since this is the base 64 string of the image, use string as the parameter type of your action method. The parameter name should match with your formdata item key(base64Image). You can generate a byte array from the base64 string in your action method. Also the image source starts with data:image/png;base64, which needs to be removed from the string before you try to convert it.
The below method accepts the string you are sending from the client, and removes the first 21 characters and use the result of that (which is now a valid base 64 string) and then creates an image from that and saves to Content/Images/ directory in the app root with a random file name.
[HttpPost]
public void SaveImage(string base64image)
{
if (string.IsNullOrEmpty(base64image))
return;
var t = base64image.Substring(22); // remove data:image/png;base64,
byte[] bytes = Convert.FromBase64String(t);
Image image;
using (MemoryStream ms = new MemoryStream(bytes))
{
image = Image.FromStream(ms);
}
var randomFileName = Guid.NewGuid().ToString().Substring(0, 4) + ".png";
var fullPath = Path.Combine(Server.MapPath("~/Content/Images/"), randomFileName);
image.Save(fullPath, System.Drawing.Imaging.ImageFormat.Png);
}
I am not 100 % sure that the default model binder can bind the base64 string to an image. If not, you can perhaps create one which does that and add that to the model binders in your system and then use the Image as the parameter type. The code inside model binder will be very similar ( read the string and generate image from that)
I am using HttpPostedFileBase.cs.
[HttpPost]
public ActionResult AddDocument(ReservationDocumentsVM reservationDocumentsVM, HttpPostedFileBase postedFile)
{
if (postedFile != null)
{
string path = Server.MapPath("~/Content/Documents/");
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
}
postedFile.SaveAs(path + Path.GetFileName(postedFile.FileName));
reservationDocumentsVM.VirtualPath = path + Path.GetFileName(postedFile.FileName);
reservationRepository.AddOrUpdateReservationDocuments(reservationDocumentsVM);
}
return RedirectToAction("Index", "Reservation");
}
Related
My problem is:
I am uploading a excel file first. After reading the file and manipulating the data, i need to generate a csv and export the same on click of the submit button.
Below is my html/javascript code:
<div>Please upload the Excel File</div>
<form method="POST" id="fileUploadForm" enctype="multipart/form-data">
<input type="file" name="file" /><br/><br/>
<input type="submit" value="Submit" id = "defaultSubmit" />
</form>
Below is the Ajax Request:
$(document).ready(function() {
$("#defaultSubmit").click(function (event) {
//stop submit the form, we will post it manually.
event.preventDefault();
// $("#fileupload").click();
// Get form
var form = $('#fileUploadForm')[0];
// Create an FormData object
var data = new FormData(form);
$.ajax({
url : "/uploadExcelFiles",
type: "POST",
enctype: 'multipart/form-data',
data: data,
processData: false,
contentType: false,
success : function(data) {
},
error : function(data) {
}
});
return false;
});
Now Below is the java code:
#RequestMapping("/uploadExcelFiles")
public void readExcelFile(HttpServletResponse response, #RequestParam("file") MultipartFile uploadedFile) {
File file = new File(uploadedFile.getOriginalFilename());
List<EmployeeData> empData = new ArrayList<>();
empData = blAttendanceService.readFile(file);
TreeMap<Object, Object> map = blAttendanceService.calculateWorkingSecondsForEmployeeInDay(empData);
List<EmployeeChartsModel> list = new LinkedList<>();
for (Entry<Object, Object> ent : map.entrySet()) {
EmployeeChartsModel ehd = new EmployeeChartsModel();
long seconds = (long) ent.getValue();
double dailyHoursSpent = (double)seconds/3600;
SimpleDateFormat sdf = new SimpleDateFormat("dd-MMM-YYYY");
System.out.println("Date::: " + sdf.format((Date)ent.getKey()) + " ::::::Hours:::: " + dailyHoursSpent);
ehd.setEmployeeDate(sdf.format((Date)ent.getKey()));
ehd.setDailyHoursSpent(dailyHoursSpent);
list.add(ehd);
}
String filename = "DailyAttendanceRecord.csv";
response.setContentType("text/csv");
response.setHeader(HttpHeaders.CONTENT_DISPOSITION,
"attachment; filename=\"" + filename + "\"");
try {
StatefulBeanToCsv<EmployeeChartsModel> writer = new StatefulBeanToCsvBuilder<EmployeeChartsModel>(response.getWriter())
.withQuotechar(CSVWriter.NO_QUOTE_CHARACTER)
.withSeparator(CSVWriter.DEFAULT_SEPARATOR)
.withOrderedResults(false)
.build();
writer.write(list);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
EmployeeChartsModel is a class for csv Model.
I am not getting any error in the code. Just the file is not exported. Also, If i read the file manually from my location and direct hit the url of this method, the file is successfully exported. But i am unable to do so through ajax post request.
Kindly suggest the changes so as to export the csv file using this ajax post request.
I am using Java, Spring Boot, Html, Javascript in my code.
I am developing web application using MVC 4 + VS 2012 + Framework 4.5.
I have three partial views, which are rendering dynamically, on my index page based on user action.
Out of three partial views, one partial view has Upload File functionality with some entry fields like textboxes.
Problem:
When user click on save button (which is present on the partial view itself). I want to save entry field into my database and stored uploaded file on shared folder.
I want to implement this using Ajax (After uploading the file and save data, user should be on the same view).
How can I implement the same? JQuery solution would be fine.
I have tried with #Ajax.BeginForm but after uploading of file, full post back happen.
Here is my small working sample, which uploads multiple files and uploads in a folder called as 'junk'
Client Side....
<html>
<head>
<title>Upload Example</title>
<script src="~/Scripts/jquery-2.1.0.intellisense.js"></script>
<script src="~/Scripts/jquery-2.1.0.js"></script>
<script src="~/Scripts/jquery-2.1.0.min.js"></script>
<script>
$(document).ready(function () {
$("#Upload").click(function () {
var formData = new FormData();
var totalFiles = document.getElementById("FileUpload").files.length;
for (var i = 0; i < totalFiles; i++)
{
var file = document.getElementById("FileUpload").files[i];
formData.append("FileUpload", file);
}
$.ajax({
type: "POST",
url: '/Home/Upload',
data: formData,
dataType: 'json',
contentType: false,
processData: false,
success: function (response) {
alert('succes!!');
},
error: function (error) {
alert("errror");
}
});
});
});
</script>
</head>
<body>
<input type="file" id="FileUpload" multiple />
<input type="button" id="Upload" value="Upload" />
</body>
</html>
Server Side....
public class HomeController : Controller
{
[HttpPost]
public void Upload( )
{
for( int i = 0 ; i < Request.Files.Count ; i++ )
{
var file = Request.Files[i];
var fileName = Path.GetFileName( file.FileName );
var path = Path.Combine( Server.MapPath( "~/Junk/" ) , fileName );
file.SaveAs( path );
}
}
}
This article helped me out: http://www.matlus.com/html5-file-upload-with-progress/
The ActionResult is still ActionResult Upload(HttpPostedFileBase file) {...}
[HttpPost]
public void Upload( )
{
for( int i = 0 ; i < Request.Files.Count ; i++ )
{
var file = Request.Files[i];
var fileName = Path.GetFileName( file.FileName );
var path = Path.Combine( Server.MapPath( "~/Junk/" ) , fileName );
file.SaveAs( path );
}
}
I am using Html5, Java script, ajax and java. I am uploading a image from desktop to the crop and after the crop it is showing in bootstrap modal in same page. But i am not getting URL for this Image, I am getting some Base64 code and when i am sending this base64 code than it is not working.
I seen this post but i did not get any solution from this link:
https://stackoverflow.com/
This code for static image, Showing first time.
My code:
HTML:
<div class="img-container">
<img src="../assets/img/picture.jpg" alt="Picture">
</div>
<div class="modal fade docs-cropped" id="getCroppedCanvasModal" aria-hidden="true" aria-labelledby="getCroppedCanvasTitle" role="dialog" tabindex="-1">
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<a class="btn btn-primary" id="download" download="cropped.png" href="javascript:void(0);">Upload</a>
</div>
</div>
Java script Code:
(function () {
var $image = $('.img-container > img');
var $download = $('#download');
$('#getCroppedCanvasModal').modal().find('.modal-body').html(result);
if (!$download.hasClass('disabled')) {
$download.attr('href', result.toDataURL());
//console.log("*****************"+result.toDataURL());
var swapUrl = result.toDataURL();
console.log("*******" + swapUrl);
// document.getElementById('replaceMe').src = swapUrl;
$('#download').click(function () {
var b = result.toDataURL();
$.ajax({
url: "/sf/p/customizeText",
type: 'GET',
data: b,
success: function (response) {
console.log("999999999999999999999999999999999----------------" + b)
},
complete: function (response) {
},
error: function (response) {
}
});
});
}
}
I am assign result.toDataURL() into variable b. But it is showing some base64 code.
How i am send this image to server.
I am giving one snippet.
Please give me some idea achieve to this solution.
Hi you can check this solution also
Javascript code
var base64before = document.querySelector('img').src;
var base64 = base64before.replace(/^data:image\/(png|jpg);base64,/, "");
var httpPost = new XMLHttpRequest();
var path = "your url";
var data = JSON.stringify(base64);
httpPost.open("POST", path, false);
// Set the content type of the request to json since that's what's being sent
httpPost.setRequestHeader('Content-Type', 'application/json');
httpPost.send(data);
This is my Java code.
public void saveImage(InputStream imageStream){
InputStream inStream = imageStream;
try {
String dataString = convertStreamToString(inStream);
byte[] imageBytes = javax.xml.bind.DatatypeConverter.parseBase64Binary(dataString);
BufferedImage image = ImageIO.read(new ByteArrayInputStream(imageBytes));
// write the image to a file
File outputfile = new File("/Users/paul/Desktop/testkey/myImage.png");
ImageIO.write(image, "png", outputfile);
}catch(Exception e) {
System.out.println(e.getStackTrace());
}
}
static String convertStreamToString(java.io.InputStream is) {
java.util.Scanner s = new java.util.Scanner(is).useDelimiter("\\A");
return s.hasNext() ? s.next() : "";
}
I am working a jQuery file upload helper and I need to understand how can I append the File from the form or the Form data as a whole to the request.
I have worked with the ASP.NET code to accept image from the Request and handle the further code, but when I try to use it using jQuery $.ajax() I can't get it to work.
I have been though Stack Overflow questions, and I have tried using FormData appending the data from the input[type="file"] (input for the file element). But each time (on the server) the block that is executed that tells me there is no file with the request.
Here is the ASP.NET code (UploadFile page)
#{
var fileName = "Not running!";
if(IsPost) {
if(Request.Files.Count > 0) {
var image = WebImage.GetImageFromRequest();
fileName = Path.GetFileName(image.FileName) + " From server";
} else {
fileName = "No file attached! From Server";
}
}
Response.Write(fileName);
}
The jQuery code is as
$(document).ready(function () {
$('form input[type=submit]').click(function () {
event.preventDefault();
$.ajax({
url: '/UploadFile',
data: new FormData().append('file',
document.getElementById("image").files[0]),
type: 'POST',
success: function (data) {
$('#result').html('Image uploaded was: ' + data);
}
});
});
});
I am already scratching my head since I can't get the file content on the serverside.
How can I send the file to the server, or the entire form data to the server, anything would be welcome!
Try using handler for this and Newtonsoft.json.dll for these purpose.
For jQuery
(document).ready(function () {
$('form input[type=submit]').click(function () {
event.preventDefault();
$.ajax({
url: 'handler.ashx', // put a handler instead of direct path
data: new FormData().append('file',
document.getElementById("image").files[0]),
type: 'POST',
success: function (data) {
$('#result').html('Image uploaded was: ' + data);
}
});
});
});
In asp.net
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
using System.Web;
using Newtonsoft.Json;
public class Handler : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
HttpPostedFile up = context.Request.Files[0];
System.IO.FileInfo upinfo = new System.IO.FileInfo(up.FileName);
System.Drawing.Image upimg = System.Drawing.Image.FromStream(up.InputStream);
string path = context.Server.MapPath("~/temp"); // this is the server path where you'll be saving your image
if (!System.IO.Directory.Exists(path))
System.IO.Directory.CreateDirectory(path);
string fileName;
fileName = up.FileName;
string newFilename = Guid.NewGuid().ToString();
System.IO.FileInfo fInfo = new System.IO.FileInfo(fileName);
newFilename = string.Format("{0}{1}", newFilename, fInfo.Extension);
string strFileName = newFilename;
fileName = System.IO.Path.Combine(path, newFilename);
up.SaveAs(fileName);
successmsg1 s = new successmsg1
{
status = "success",
url = "temp/" + newFilename,
width = upimg.Width,
height = upimg.Height
};
context.Response.Write(JsonConvert.SerializeObject(s));
}
I tried to implement Jquery.Spell.Checker in asp.net application but it gives error as shown in following image.
Anyone suggest me how to resolve it.
CLICK HERE TO SEE THE SAMPLE
PS:
I have done changes in my application but still doesn't working and display alert message as per above image.Please let me know if i was missing something.The code given below:
LINK:
<link href="JQuerySpellChecker/spellchecker.css" rel="stylesheet" type="text/css" />
<script src="JavaScript/jquery-1.4.4.min.js" type="text/javascript"></script>
<script src="JQuerySpellChecker/jquery.spellchecker.js" type="text/javascript"></script>
CSS:
<style type="text/css">
body {
margin: 1em;
font-family: 'lucida grande',helvetica,verdana,arial,sans-serif;
}
#textarea-example {
width: 562px;
}
textarea {
font-size: 90%;
margin-bottom:10px;
padding: 5px;
border: 1px solid #999999;
border-color: #888888 #CCCCCC #CCCCCC #888888;
border-style: solid;
height: 20em;
width: 550px;
}
button {
font-size: 90%;
cursor: pointer;
}
.loading {
padding: 0.5em 8px;
display: none;
font-size: small;
}
</style>
HTML:
<div id="textarea-example">
<p>
<label for="text-content">Add your own text and check the spelling.</label>
</p>
<textarea id="text-content" rows="5" cols="25"></textarea>
<div>
<button id="check-textarea">Check Spelling</button>
<span class="loading">loading..</span>
</div>
</div>
JAVASCRIPT:
// check the spelling on a textarea
$("#check-textarea").click(function(e){
e.preventDefault();
$(".loading").show();
$("#text-content")
.spellchecker({
url: "CheckSpelling.aspx", // default spellcheck url
lang: "en", // default language
engine: "google", // pspell or google
addToDictionary: false, // display option to add word to dictionary (pspell only)
wordlist: {
action: "after", // which jquery dom insert action
element: $("#text-content") // which object to apply above method
},
suggestBoxPosition: "below", // position of suggest box; above or below the highlighted word
innerDocument: false // if you want the badwords highlighted in the html then set to true
})
.spellchecker("check", function(result){
// spell checker has finished checking words
$(".loading").hide();
// if result is true then there are no badly spelt words
if (result) {
alert('There are no incorrectly spelt words.');
}
});
});
// you can ignore this; if document is viewed via subversion in google code then re-direct to demo page
if (/jquery-spellchecker\.googlecode\.com/.test(window.location.hostname) && /svn/.test(window.location)) {
window.location = 'http://spellchecker.jquery.badsyntax.co.uk/';
}
CheckSpelling.aspx
protected void Page_Load(object sender, EventArgs e)
{
string str = Request["str"];
//string str = "goood";
if (str != null)
{
string url = "https://www.google.com";
string path = "/tbproxy/spell?lang=en&hl=en";
// setup XML request
string xml = "<?xml version=\"1.0\" encoding=\"utf-8\" ?>";
xml += "<spellrequest textalreadyclipped=\"0\" ignoredups=\"0\" ignoredigits=\"1\" ignoreallcaps=\"1\">";
xml += "<text>" + str + "</text></spellrequest>";
ASCIIEncoding encoding = new ASCIIEncoding();
byte[] data = encoding.GetBytes(xml);
WebProxy objWP = new WebProxy("address", 1978);
objWP.Credentials = new NetworkCredential("mysystemname", "password");
System.Net.HttpWebRequest request = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(url + path);
request.Proxy = objWP;
request.Method = "POST";
request.ContentType = "text/xml";
request.ContentLength = data.Length;
System.IO.Stream stream = request.GetRequestStream();
// Send the data.
stream.Write(data, 0, data.Length);
stream.Close();
// Get the response.
System.Net.WebResponse response = request.GetResponse();
// Get the stream containing content returned by the server.
stream = response.GetResponseStream();
// Open the stream using a StreamReader for easy access.
System.IO.StreamReader reader = new System.IO.StreamReader(stream);
// Read the content.
string responseFromServer = reader.ReadToEnd();
// Clean up the streams.
reader.Close();
stream.Close();
response.Close();
Response.ContentType = "text/xml";
MatchCollection result = Regex.Matches(responseFromServer, "<c o=\"([^\"]*)\" l=\"([^\"]*)\" s=\"([^\"]*)\">([^<]*)</c>");
if (result != null && result.Count > 0)
Response.Write(result[0].Value);
}
Response.Write("Failed");
}
You need to write yourself an ASP version of the included PHP server side file. Essentially, the server side component proxies a request off to Google or uses a PHP spell checker. Since you wouldn't really want to convert the whole of the Pspell library, I would recommend simply wrapping up the call to Google's spell check site.
i.e. Create an ASPX page and add the following code to it
<%# Import Namespace="System.Xml" %>
<script language="C#" runat="server">
public void Page_Load(Object src, EventArgs e)
{
var str = Request["str"];
if (str != null)
{
var url = "https://www.google.com";
var path = "/tbproxy/spell?lang=en&hl=en";
// setup XML request
var xml = "<?xml version=\"1.0\" encoding=\"utf-8\" ?>";
xml += "<spellrequest textalreadyclipped=\"0\" ignoredups=\"0\" ignoredigits=\"1\" ignoreallcaps=\"1\">";
xml += "<text>" + str + "</text></spellrequest>";
ASCIIEncoding encoding = new ASCIIEncoding();
byte[] data = encoding.GetBytes(xml);
System.Net.HttpWebRequest request = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(url + path);
request.Method = "POST";
request.ContentType = "text/xml";
request.ContentLength = data.Length;
System.IO.Stream stream = request.GetRequestStream();
// Send the data.
stream.Write(data, 0, data.Length);
stream.Close();
// Get the response.
System.Net.WebResponse response = request.GetResponse();
// Get the stream containing content returned by the server.
stream = response.GetResponseStream();
// Open the stream using a StreamReader for easy access.
System.IO.StreamReader reader = new System.IO.StreamReader(stream);
// Read the content.
string responseFromServer = reader.ReadToEnd();
// Clean up the streams.
reader.Close();
stream.Close();
response.Close();
Response.ContentType = "text/xml";
MatchCollection result = Regex.Matches(responseFromServer, "<c o=\"([^\"]*)\" l=\"([^\"]*)\" s=\"([^\"]*)\">([^<]*)</c>");
if (result != null && result.Count > 0)
Response.Write(result[0].Value);
}
Response.Write("Failed");
}
</script>
Then change the call in the js to call your new aspx file rather than the 'checkspelling.php'
Might be a bit late for you, but for any one else trying to resolve this problem, Jack Yang has produced an ASP implementation of checkspelling.php it can be found at
https://github.com/jackmyang/jQuery-Spell-Checker-for-ASP.NET
The plugin only does the client-side code. You'll have to supply it with your ASP script's URL.
Read the documentation.