gpt4 book ai didi

javascript - 是否可以仅通过 $.ajax(options) 或 xhr.send(file) 上传文件?

转载 作者:技术小花猫 更新时间:2023-10-29 12:43:50 27 4
gpt4 key购买 nike

我正在使用文件 api 和 xhr2 规范。我创建了一个使用 FormData 的 uploader (由旧浏览器的 flash 支持)和 $.ajax(options)其中 FormData 对象带有 Fileoptions.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 多部分/表单数据请求发送,但没有包含文件的多部分正文

如果我把它放入 options.data = {file: file};无论是否processData,它都会被序列化属性是否设置为真。

最佳答案

您可以从使用 FileReader 或类似 API 读取的 HTML5 文件数据中手动生成用于上传的 MIME 数据。查看:https://github.com/coolaj86/html5-formdata .这将或多或少地做到这一点,尽管它取决于 getAsBinary() - 将其更改为也能够使用 FileReaderreadAsBinaryString() 可能会更跨浏览器兼容。

请注意,这在 IE7/8 中仍然根本不起作用,正如其他人所说,如果不求助于 Flash 或 iframe,就无法做到这一点。话虽这么说,如果您使用的是文件,大概您根本不关心 IE7 或 IE8...

关于javascript - 是否可以仅通过 $.ajax(options) 或 xhr.send(file) 上传文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6107835/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com