[英]How to attach FormData to an XMLHttpRequest
我有一个这样的jQuery请求
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) {
}
});
}
可以很好地用于上传图像并将其发送到服务器。 但是它不处理二进制返回类型(用于接收二进制格式的图像)。
然后我在这里有其他代码
// 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();
};
可以处理我需要的规范。 但是问题是,如何修改此工作代码,以便可以将FormData()对象与图像相连?
谢谢
您可以按如下所示进行附加:
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.
}
修改代码需要它将请求类型更改为POST并将FormData对象传递给send方法
// 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);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.