I have a jquery request like this
function sendData() {
var formData = new FormData($("#myform")[0]);
$.ajax({
type: 'POST',
url: "/process",
data: formData,
dataType: 'json',
contentType:false,
cache:false,
processData:false,
timeout: 30 * 1000,
beforeSend: function( xhr ) {
},
success: function(jsonData,status,xhr) {
},
error: function(data,status,xhr) {
}
});
}
which works fine for uploading an image and sending it to server. But it does not handle binary return types (for receiving images in binary format).
Then I have this other code here
// http://www.henryalgus.com/reading-binary-files-using-jquery-ajax/
function fetchBlob(uri, callback) {
var xhr = new XMLHttpRequest();
xhr.open('GET', uri, true);
xhr.responseType = 'arraybuffer';
xhr.onload = function(e) {
if (this.status == 200) {
var blob = this.response;
if (callback) {
callback(blob);
}
}
};
xhr.send();
};
which handles the specification I need. But the problem is, how do I modify this working code so that I can attach a FormData() object with an image?
Thanks
You can attach it as below:
function fetchBlob(uri, callback) {
var formData = new FormData($("#myform")[0]);
var xhr = new XMLHttpRequest();
xhr.open('GET', uri, true);
xhr.responseType = 'arraybuffer';
xhr.onload = function(e) {
if (this.status == 200) {
var blob = this.response;
if (callback) {
callback(blob);
}
}
};
xhr.send(formData); //attach it here.
}
The modification the code needs it to change the request type to POST and pass the FormData object to the send method
// http://www.henryalgus.com/reading-binary-files-using-jquery-ajax/
function fetchBlob(uri, callback) {
var xhr = new XMLHttpRequest();
xhr.open('POST', uri, true);
xhr.responseType = 'arraybuffer';
var formData = new FormData($("#myform")[0]);
xhr.onload = function(e) {
if (this.status == 200) {
var buffer = this.response;
if (callback) {
callback(buffer);
}
}
};
xhr.send(formData);
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.