JavaScript >> Javascript 文檔 >  >> JavaScript

如何使用 XMLHttpRequest (XHR) 監控進度

XMLHttpRequest (XHR) 允許我們偵聽在處理 HTTP 請求時可能發生的各種事件。這包括錯誤通知、定期進度通知、請求中止通知等。

在本文中,您將學習如何監控 文件下載和上傳進度 在 JavaScript 中使用 XHR 事件。

監控下載進度

一個這樣的事件是 progress 下載開始時觸發。例如,當您發佈內容時,XMLHttpRequest 會先將我們的數據(請求體)上傳到服務器,然後再下載響應。

您可以將此事件與 load 一起使用 跟踪文件下載狀態。這是一個例子:

const xhr = new XMLHttpRequest();

// listen for `load` event
xhr.onload = () => {
    console.log(`The transfer is completed: ${xhr.status} ${xhr.response}`);
};

// listen for `error` event
xhr.onerror = () => {
    console.error('Download failed.');
}

// listen for `abort` event
xhr.onabort = () => {
    console.error('Download cancelled.');
}

// listen for `progress` event
xhr.onprogress = (event) => {
    // event.loaded returns how many bytes are downloaded
    // event.total returns the total number of bytes
    // event.total is only available if server sends `Content-Length` header
    console.log(`Downloaded ${event.loaded} of ${event.total} bytes`);
}

// open and send request
xhr.open('GET', '/download-attachment');
xhr.send();

正如您在上面看到的,我們為使用 XMLHttpRequest 從服務器下載數據時可以觸發的事件添加了幾個事件監聽器 .

進度事件處理程序,由 xhr.onprogress 指定 上面的函數在事件的 total 中獲取要傳輸的總字節數以及到目前為止傳輸的字節數 和 loaded 屬性。

監控上傳進度

XMLHttpRequest 為下載和上傳傳輸提供進度事件。下載事件直接在 XMLHttpRequest 上觸發 對象,正如我們在上面的例子中看到的那樣。

對於上傳傳輸,事件在 XMLHttpRequest.upload 對像上觸發;一個沒有方法的對象,專門用於跟踪上傳事件。

上傳對象提供自己的事件,類似於 XMLHttpRequest 可用於監控上傳。這是一個例子:

const xhr = new XMLHttpRequest();

// listen for `upload.load` event
xhr.upload.onload = () => {
    console.log(`The upload is completed: ${xhr.status} ${xhr.response}`);
};

// listen for `upload.error` event
xhr.upload.onerror = () => {
    console.error('Upload failed.');
}

// listen for `upload.abort` event
xhr.upload.onabort = () => {
    console.error('Upload cancelled.');
}

// listen for `progress` event
xhr.upload.onprogress = (event) => {
    // event.loaded returns how many bytes are downloaded
    // event.total returns the total number of bytes
    // event.total is only available if server sends `Content-Length` header
    console.log(`Uploaded ${event.loaded} of ${event.total} bytes`);
}

// open request
xhr.open('POST', '/upload-file');

// prepare a file object
const files = document.querySelector('[name=file]').files;
const formData = new FormData();
formData.append('avatar', files[0]);

// send request
xhr.send(formData);

看看如何使用XHR上傳文件的教程,看一個JavaScript上傳文件的實際例子。


Tutorial JavaScript 教程
  1. 是否可以使用 JavaScript / jQuery 進行 base 36 編碼?

  2. 使用 Web Audio Api 和 Chromium 消除迴聲

  3. 使用 `.new` 鏈接提高您的工作效率⏱️!

  4. 如何在 TypeScript 中以專業人士的身份輸入 React 道具

  5. jQuery 檢查 Flash 是否啟用

  6. 了解 HOF(高階函數)

  7. 使用 VueJS 和 Ably 實現實時地理位置跟踪器

  1. 學習解構

  2. 250+ JS 資源來掌握編程💥 備忘單

  3. 使用 apply() 和 call() 方法調用函數

  4. 在 GitHub 上獲得了新徽章。

  5. JavaScript 函數調用() |代碼

  6. 軟件質量保證工程師的角色和職責是什麼?

  7. 總結 Namaste 🙏 JavaScript EP02(Js代碼如何執行和調用棧)

  1. 為多個工作區著色您的 VS 代碼

  2. Node.js 和 TypeScript 中的依賴注入和反轉指南

  3. LeetCode - 在每個節點中填充下一個右指針

  4. 在 JavaScript 中操作數組