我正在 try catch Fetch 请求的下载进度并使用它来更改进度条的宽度。我将 ProgressEvent.lengthComputable 视为一种潜在的解决方案,但不确定这是否可以与 Fetch API 一起使用。
最佳答案
不检查错误(如 try/catch 等)
const elStatus = document.getElementById('status');
function status(text) {
elStatus.innerHTML = text;
}
const elProgress = document.getElementById('progress');
function progress({loaded, total}) {
elProgress.innerHTML = Math.round(loaded/total*100)+'%';
}
async function main() {
status('downloading with fetch()...');
const response = await fetch('https://fetch-progress.anthum.com/30kbps/images/sunrise-baseline.jpg');
const contentLength = response.headers.get('content-length');
const total = parseInt(contentLength, 10);
let loaded = 0;
const res = new Response(new ReadableStream({
async start(controller) {
const reader = response.body.getReader();
for (;;) {
const {done, value} = await reader.read();
if (done) break;
loaded += value.byteLength;
progress({loaded, total})
controller.enqueue(value);
}
controller.close();
},
}));
const blob = await res.blob();
status('download completed')
document.getElementById('img').src = URL.createObjectURL(blob);
}
main();
<div id="status"> </div>
<h1 id="progress"> </h1>
<img id="img" />
改编自 here
关于javascript - 获取 API 下载进度指示器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47285198/