1.xhr(即可監(jiān)聽上傳進(jìn)度,也可以監(jiān)聽下載進(jìn)度)
const request = (options = {}) => {
const { url, method, data } = options;
return new Promise((resolve) => {
const xhr = new XMLHttpRequest();
xhr.addEventListener('readystatechange', () => {
if (xhr.readyState === xhr.DONE) {
resolve(xhr.responseText);
}
})
// 提交數(shù)據(jù)的進(jìn)度
xhr.upload.addEventListener('progress', (e) => {
// 當(dāng)前上傳的字節(jié)長度,總的字節(jié)長度
console.log(e.loaded, e.total);
})
// 接受數(shù)據(jù)的進(jìn)度
xhr.addEventListener('progress', (e) => {
// 當(dāng)前接受的字節(jié)長度,總的字節(jié)長度
console.log(e.loaded, e.total);
})
xhr.open(method, url);
xhr.send(data);
})
}
2.fetch(只能監(jiān)聽數(shù)據(jù)的下載進(jìn)度)
const request = (options = {}) => {
const { url, method, data } = options;
return new Promise(async (resolve) => {
const resp = await fetch(url, {
body: data
})
const total = resp.headers.get('content-length');
const decoder = new TextDecoder();
let body = '';
const reader = resp.body?.getReader();
let loaded = 0;
while (1) {
const { done, value } = await reader?.read();
if (done) {
break;
}
loaded += value.length;
body += decoder.decode(value);
// 數(shù)據(jù)的總長度,當(dāng)前接受的長度
console.log(total, loaded)
}
resolve(body)
})
}
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。