jQuery的相当于XMLHtt prequest的上传? [英] jQuery equivalent to XMLHttpRequest's upload?
问题描述
与HTML5的文件API的工作,上载是通过所谓的对象所作的上传
在 XMLHtt prequest
。 这是我工作的教程(和<一href="http://webcache.googleusercontent.com/search?q=cache%3aF27n8Za7Lt4J%3arobertnyman.com/html5/fileapi-upload/fileapi-upload.html+http://robertnyman.com/html5/fileapi-upload/fileapi-upload.html&cd=1&hl=en&ct=clnk&client=firefox-a&source=www.google.com">Google高速缓存镜像因为它是下降的时刻)。这是有关部分:
Working with HTML5's File API, the upload is made via an object called upload
in the XMLHttpRequest
. This is the tutorial I'm working with (and the Google cache mirror since it's down at the moment). This is the relevant part:
// Uploading - for Firefox, Google Chrome and Safari
xhr = new XMLHttpRequest();
// Update progress bar
xhr.upload.addEventListener("progress", function (evt) {
正如你所看到的,跟踪上传进度,在 XMLHtt prequest
对象有一个命名属性上传
,这是我们可以添加一个事件处理程序。
As you can see, to track the upload progress, the XMLHttpRequest
object has a property named upload
, which we can add an event handler.
我的问题是:已经jQuery的等效?。我试图离开code一样干净和跨浏览器越好,只要兼容微软认为这是一个好主意(尽管它听起来像的它会在2012年或2013 )。
My question is: has jQuery an equivalent?. I'm attempting to leave the code as clean as and cross-browser compatible as possible, for whenever Microsoft thinks it's a good idea (although it sounds like it will be in 2012 or 2013).
推荐答案
下面是我想出了要解决的问题。该$。阿贾克斯()调用允许提供一个回调来生成XHR。调用请求之前,我只产生一个,设置它,然后创建一个封闭返回它的时候$。阿贾克斯()会需要它。这本来是容易得多,如果他们只是通过jqxhr给访问它,但他们没有。
Here is what I came up with to get around the issue. The $.ajax() call allows to provide a callback to generate the XHR. I just generate one before calling the request, set it up and then create a closure to return it when $.ajax() will need it. It would have been much easier if they just gave access to it through jqxhr, but they don't.
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);
这篇关于jQuery的相当于XMLHtt prequest的上传?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!