Reputation: 55
I am trying to send one image from canvas and save it at server using ajax. My Jquery code is like:
$(document).ready(function () {
$("#UpLoad").click(function () { // trick by a button
var canVas = $('#Canvas')[0];
var dataURL = canVas.toDataURL();
$.ajax({
type: "POST",
url: 'savePicture.php',
data: { imgBase64: dataURL },
cache:false,
success: function (data) {
console.log("success");
console.log(data);
},
error: function (data) {
console.log("error");
console.log(data);
}
});
});
});
But when I checked with the console, i sent a blank data file (since I console log the data I was sending.
Can anyone help? Thanks.
Upvotes: 0
Views: 1381
Reputation: 877
Please give credit to the below post! Convert Data URI to File then append to FormData
$(document).ready(function() {
function dataURItoBlob(dataURI) {
// convert base64/URLEncoded data component to raw binary data held in a string
var byteString;
if (dataURI.split(',')[0].indexOf('base64') >= 0)
byteString = atob(dataURI.split(',')[1]);
else
byteString = unescape(dataURI.split(',')[1]);
// separate out the mime component
var mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0];
// write the bytes of the string to a typed array
var ia = new Uint8Array(byteString.length);
for (var i = 0; i < byteString.length; i++) {
ia[i] = byteString.charCodeAt(i);
}
return new Blob([ia], {
type: mimeString
});
}
$("#UpLoad").click(function() { // trick by a button
var canVas = $('#Canvas')[0];
var dataURL = canVas.toDataURL();
var blob = dataURItoBlob('dataURL');
var formData = new FormData();
formData.append('imgBase64', blob);
$.ajax({
type: "POST",
url: 'savePicture.php',
data: formData,
contentType: false, //need this
processData: false, //need this
cache: false,
success: function(data) {
console.log("success");
console.log(data);
},
error: function(data) {
console.log("error");
console.log(data);
}
});
});
});
Upvotes: 1