1.xhr(即可监听上传进度,也可以监听下载进度)
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);
}
})
// 提交数据的进度
xhr.upload.addEventListener('progress', (e) => {
// 当前上传的字节长度,总的字节长度
console.log(e.loaded, e.total);
})
// 接受数据的进度
xhr.addEventListener('progress', (e) => {
// 当前接受的字节长度,总的字节长度
console.log(e.loaded, e.total);
})
xhr.open(method, url);
xhr.send(data);
})
}
2.fetch(只能监听数据的下载进度)
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);
// 数据的总长度,当前接受的长度
console.log(total, loaded)
}
resolve(body)
})
}