【发布时间】:2011-08-31 18:12:46
【问题描述】:
我正在使用文件 api 和 xhr2 规范。我创建了一个使用FormData 和$.ajax(options) 的上传器(由旧浏览器支持的flash),其中带有File 的FormData 对象是options.data 对象的一部分。一切正常。
现在我决定删除FormData,因为浏览器支持较弱。除了
var xhr = new XMLHttpRequest();
xhr.setRequestHeader("Cache-Control", "no-cache");
xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest");
xhr.setRequestHeader("X-File-Name", file.name);
xhr.send(file);
它不会返回我可以在递归函数中使用的 Promise。
我的代码是这样的:
startUpload: function() {
var that = this;
that.recurseSend(that.queue);
},
_initProgressListener: function (options, file) {
var that = this;
var xhr = $.ajaxSettings.xhr();
options.contentType = 'multipart/form-data';
options.processData = false;
options.type = 'POST';
// WHAT TO DO HERE TO avoid FormData???? What ever I put into options.data - fails
/* THIS WOULD WORK
var formData = new FormData();
formData.append('file', file);
options.data = formData;
*/
if (xhr.upload && xhr.upload.addEventListener) {
xhr.upload.addEventListener('progress', function (e) {
that._onProgress(e, file);
}, false);
options.xhr = function () {
return xhr;
};
}
},
recurseSend: function (queue) {
var file = queue.pop();
if(file != undefined) {
var that = this;
var options = that.options;
that._initProgressListener(options, file);
var send = function() {
jqXHR = ($.ajax(options)).done(function(result, textStatus, jqXHR) {
that._onDone(result, textStatus, jqXHR, file);
queue.stats['successful_uploads']++;
}).fail(function(jqXHR, textStatus, errorThrown) {
that._onFail(jqXHR, textStatus, errorThrown, file);
queue.stats['upload_errors']++;
}).always(function(result, textStatus, jqXHR) {
that._onAlways(result, textStatus, jqXHR, file);
queue.stats['files_queued']--;
that.recurseSend(queue);
});
return jqXHR;
};
this._beforeSend(file);
return send();
}
},
简而言之,$.ajax(options) 解析为 xhr.send(formData) 如果 options.data = FormData 但我如何使其解析为 xhr.send(file) ?
已编辑:我正在玩它,如果我设置 options.data = file;然后 $.ajax(options) 执行 xhr.send(theFile);但有错误Error: INVALID_STATE_ERR: DOM Exception 11
请求作为 POST multipart/form-data 请求发送,但没有包含文件的多部分正文
如果我把它放到options.data = {file: file}; 中,无论processData 属性是否设置为true,它都会被序列化。
【问题讨论】:
标签: javascript jquery ajax html file-upload