fetch(url).then((response) => {
if (response.status == 200) {
// 进度条相关
// 获取 Response 对象的 body 属性的读取器(reader)。body 属性是一个可读的流(ReadableStream),可以用来读取响应体的数据。
const reader = response.body.getReader();
const contentLength = +response.headers.get('Content-Length');
let receivedLength = 0;
let chunks = [];
// 读取一个数据块。这个方法返回一个 Promise,当一个数据块被读取时,这个 Promise 就会解析为一个包含 done 和 value 属性的对象。done 属性表示是否已经读取完所有数据,value 属性是一个 Uint8Array,包含了读取到的数据块。
return reader.read().then(function processChunk({ done, value }) {
if (done) {
// 将 chunks 数组中的所有数据块复制到一个新的 Uint8Array 中,然后使用这个 Uint8Array 创建一个 Blob 对象
let data = new Uint8Array(receivedLength);
let position = 0;
for(let chunk of chunks) {
data.set(chunk, position);
position += chunk.length;
}
return new Blob([data]);
}
// 将读取到的数据块添加到 chunks 数组中。
chunks.push(value);
// 更新已接收的数据长度。
receivedLength += value.length;
console.log(`已下载:${receivedLength},总大小:${contentLength}`);
// 递归调用 reader.read(),直到读取完所有数据。
return reader.read().then(processChunk);
});
} else {
console.log('下载失败')
}
})
.then((blob) => {
console.log('下载完成');
//保存文件
})
fetch下载进度条
最新推荐文章于 2024-12-26 09:13:17 发布