Upload progress (with or w/o XMLHttpRequest 2) with Javascript

我的未来我决定 提交于 2019-12-06 06:24:38

问题


XMLHttpRequest 2 has a new thing. It can upload files. I got that working (it's super easy). Now I'm wondering if there's a way to get the upload progress of that file. I wouldn't be interested in this normally, but in Google Chrome (8) I saw that the onreadystatechange event is a XMLHttpRequestProgressEvent. Progress... There's nothing in there about upload progress (just request state), but it made me wondering.

Google Chrome has a progress 'counter' when uploading big files natively. It's standard. It's always there and unconfigurable. It's in the statusbar. Is something like that possible with Javascript? I'd like to put it in a nice <progress> element or something.

I don't want SWF or Java uploaders (with polling and >JS callbacks). It has to be native. If the browser can do it, these days Javascript should be able to do it, right!? =)

In case of no XMLHttpRequest 2, I guess it wouldn't be possible with the very standard file upload (no ajax and just a <input type=file>).

Thanks for the info


回答1:


Hook the progress event. That will give you progress for all requests. Check first to see if the upload object is available -- that will give you progress for only the upload part.

Something like this:

var xhr; // this is your XMLHttpRequest

// hook to upload events if available, otherwise snag all progress events
var eventSource = xhr.upload || xhr;

eventSource.addEventListener("progress", function(e) {
    // normalize position attributes across XMLHttpRequest versions and browsers
    var position = e.position || e.loaded;
    var total = e.totalSize || e.total;

    // TODO: display progress
});


来源:https://stackoverflow.com/questions/4411566/upload-progress-with-or-w-o-xmlhttprequest-2-with-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!