【发布时间】:2022-01-07 23:17:20
【问题描述】:
我正在寻找一种在我的 React 应用程序中获取获取请求进度的方法?有什么方法可以插入 fetch API 以获取某种类型的请求的加载百分比,我可以使用它来显示给我的用户?
【问题讨论】:
-
这能回答你的问题吗? Fetch API Download Progress Indicator?
我正在寻找一种在我的 React 应用程序中获取获取请求进度的方法?有什么方法可以插入 fetch API 以获取某种类型的请求的加载百分比,我可以使用它来显示给我的用户?
【问题讨论】:
使用 fetch 方法
要跟踪下载进度,我们可以使用 response.body 属性。 它是一个 ReadableStream——一个特殊的对象,它提供了一个块一个块的主体。 Streams API 规范中描述了可读流。 与response.text()、response.json()等方法不同,response.body可以完全控制读取过程,我们可以随时统计消耗了多少。
// Start the fetch and obtain a reader
let response = await fetch(url);
const reader = response.body.getReader();
// get total length
const contentLength = +response.headers.get('Content-Length');
// read the data
let receivedLength = 0; // received that many bytes at the moment
let chunks = []; // array of received binary chunks (comprises the body)
while(true) {
const {done, value} = await reader.read();
if (done) {
break;
}
chunks.push(value);
receivedLength += value.length;
console.log(`Received ${receivedLength} of ${contentLength}`)
}
请注意,目前无法在 fetch 方法中上传曲目。为此,我们应该使用 XMLHttpRequest。
参考:https://javascript.info/fetch-progress
使用 axios 类:
axios.request({
method: "post",
url: url,
data: data,
onUploadProgress: (p) => {
console.log(progress);
}
}).then (data => {
})
【讨论】: