使用 HTML5 的文件 API,通过名为的对象进行上传upload
in the XMLHttpRequest
. This是我正在使用的教程(以及谷歌缓存镜像因为目前它已关闭)。这是相关部分:
// Uploading - for Firefox, Google Chrome and Safari
xhr = new XMLHttpRequest();
// Update progress bar
xhr.upload.addEventListener("progress", function (evt) {
如您所见,为了跟踪上传进度,XMLHttpRequest
对象有一个名为upload
,我们可以添加一个事件处理程序。
我的问题是:jQuery 有等效的吗?。我试图让代码尽可能干净和跨浏览器兼容,只要微软认为这是一个好主意(尽管听起来像会在2012年或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);
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)