如何使用 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上傳文件的實際例子。