在jQuery 1.5+ 的jqXHR上監聽檔案上傳進度(xhr.upload)

來源:互聯網
上載者:User
XMLHttpRequest.upload

在Firefox, Google Chrome and Safari中,如果通過XMLHttpRequest上傳檔案,
是可以通過監聽XMLHttpRequest.upload對象的progress事件來查看進度的。

var xhr = new XMLHttpRequest();xhr.upload.addEventListener("progress", function (evt) {    // display uploading progress infomation...});
xhr.upload在jQuery中消失了?

在看完JQuery最佳實務後,
決定使用最新版本的jQuery 1.6.2替換一下正在使用的1.4.2,果然,效能在感覺上有提升。
可是悲劇的發現,怎麼上傳檔案的進度不見了。調試發現,原來xhr.upload不見了。

查看jQuery的jqXHR文檔,
發現jqXHR不是XMLHttpRequest的簡單擴充。

怎樣才能拿到原始的XMLHttpRequest?

只要在$.ajax請求中拿到原始的XMLHttpRequest,然後監聽upload對象的progress事件,就可以解決此問題了。
於是乎,為了拿到原始的XMLHttpRequest,我們需要寫一小段代碼。

根據jQuery.ajax文檔,xhr是可以自己提供的:

xhr: Function    Default: ActiveXObject when available (IE),     the XMLHttpRequest otherwise Callback for creating     the XMLHttpRequest object.     Defaults to the ActiveXObject when available (IE),     the XMLHttpRequest otherwise.     Override to provide your own implementation for     XMLHttpRequest or enhancements to the factory.

於是,我們就可以自己提供xhr,然後設定progress事件:

function onprogress(evt) {    // display uploading progress infomation...};var xhr_provider = function() {    var xhr = jQuery.ajaxSettings.xhr();    if(onprogress && xhr.upload) {        xhr.upload.addEventListener('progress', onprogress, false);    }    return xhr;};$.ajax({    url: url,    timeout: 5*60*1000,    type : 'post',    data: bb.getBlob(),    contentType: 'multipart/form-data; boundary=' + boundary,    processData: false,    xhr: xhr_provider,    success: function() {},    error: function() {}});
有愛

其實本文主要目的是推廣"JQuery最佳實務",
趕緊看,然後趕緊看看自己如何使用jQuery的。

希望本文對你有用。 ^_^

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.