gpt4 book ai didi

javascript - jQuery 相当于 XMLHttpRequest 的上传?

转载 作者:可可西里 更新时间:2023-11-01 02:33:57 25 4
gpt4 key购买 nike

使用 HTML5 的文件 API,上传是通过 XMLHttpRequest 中名为 upload 的对象进行的。 This是我正在使用的教程(以及 Google cache mirror,因为它目前已关闭)。这是相关部分:

// Uploading - for Firefox, Google Chrome and Safari
xhr = new XMLHttpRequest();

// Update progress bar
xhr.upload.addEventListener("progress", function (evt) {

如您所见,为了跟踪上传进度,XMLHttpRequest 对象有一个名为upload 的属性,我们可以为它添加一个事件处理程序。

我的问题是:jQuery 有等效项吗?。我试图让代码尽可能干净和跨浏览器兼容,因为只要微软认为这是个好主意(尽管听起来像 it will be in 2012 or 2013 )。

最佳答案

这是我想出的办法来解决这个问题。 $.ajax() 调用允许提供回调以生成 XHR。我只是在调用请求之前生成一个,设置它然后创建一个闭包以在 $.ajax() 需要它时返回它。如果他们只是通过 jqxhr 授予访问权限会容易得多,但他们没有。

var reader = new FileReader();

reader.onloadend = function (e) {
var xhr, provider;

xhr = jQuery.ajaxSettings.xhr();
if (xhr.upload) {
xhr.upload.addEventListener('progress', function (e) {
// ...
}, false);
}
provider = function () {
return xhr;
};

// Leave only the actual base64 component of the 'URL'
// Sending as binary ends up mangling the data somehow
// base64_decode() on the PHP side will return the valid file.
var data = e.target.result;
data = data.substr(data.indexOf('base64') + 7);

$.ajax({
type: 'POST',
url: 'http://example.com/upload.php',
xhr: provider,
dataType: 'json',
success: function (data) {
// ...
},
error: function () {
// ...
},
data: {
name: file.name,
size: file.size,
type: file.type,
data: data,
}
});
};
reader.readAsDataURL(file);

关于javascript - jQuery 相当于 XMLHttpRequest 的上传?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5157361/

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