If you were asking "upload images via AJAX", using the FormData
the answer can be simpler and easily searchable on the internet.
Kindly see if this link
addresses your question.
To get an image from the DOM, you would use the same above. But instead of submitting the form, you would be reading the DOM img element as a dataURI
.
Check the FIDDLE for the following code's HTML:
var originalImage = document.getElementById("image"),
canvas = document.getElementById('canvas'),
context = canvas.getContext('2d'),
formdata = false,
dummy = document.getElementById('dummy'),
newImage = new Image();
if (window.FormData) {
formdata = new FormData();
}
newImage.onload = function(){
// width and height here should be the same as original image
// detect before-hand, using jQuery(el).width() /.height() on the DOM element
context.drawImage(newImage, 0, 0, 400, 300);
}
newImage.src = originalImage.src;
// traditional ajax and jQuery, no HTML5
if (formdata) {
var canvasToDURI = canvas.toDataURL();
formdata.append("image-data", canvasToDURI);
// yay!, jQuery
$.ajax({
url: "upload.php",
type: "POST",
data: formdata,
processData: false,
contentType: false,
success: function (res) {
// do some thing !
dummy.innerText = 'Image data sent !';
},
error: function(a, b, c) {
dummy.innerText = 'The following data was not sent due to : ' + b + ' -- '+ c + ' \n\n' + canvasToDURI;
}
});
}
If FormData
is also not supported, you can create a form element
and change the enctype
of the form
to "multipart/form-data"
and send the data using JavaScript in an AJAX call, without submitting the form.