下载文件并展示进度条
有时候要下载的文件是跨域的,或者有其他配置,或者是浏览器可以直接打开的文件MIME类型,那么单纯的使用创建a标签并绑定href和download可能并不会下载,而是会跳转并打开文件。
这时就需要用fetch或其他方式来实现下载功能,然而在下载过程中,用户是无感知的,所以需要有一个进度条来展示下载进度
详见以下代码块:
fetch(url)
.then((response) => {
if (response.status === 200) {
const reader = response.body.getReader();
const contentLength = +response.headers.get('Content-Length');
let receivedLength = 0;
let chunks = [];
return reader.read().then(function processChunk({ done, value }) {
if (done) {
console.log('下载完成');
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.push(value);
receivedLength += value.length;
console.log(`已下载:${receivedLength},总大小:${contentLength}`);
return reader.read().then(processChunk);
});
} else {
console.log('下载失败')
}
})
.then((blob) => {
const blobUrl = window.URL.createObjectURL(blob)
const aEl = document.createElement('a')
aEl.href = blobUrl
aEl.download = filename
aEl.click()
window.URL.revokeObjectURL(blobUrl)
console.log("下载成功")
})
.finally(() => {
})