下载文件进度条的JavaScript特效主要涉及以下几个基础概念:
以下是一个使用Fetch API和XMLHttpRequest实现下载进度条的简单示例:
function downloadFile(url) {
fetch(url, { method: 'GET' })
.then(response => {
const reader = response.body.getReader();
const contentLength = +response.headers.get('Content-Length');
let receivedLength = 0;
const chunks = [];
while (true) {
const { done, value } = await reader.read();
if (done) {
break;
}
chunks.push(value);
receivedLength += value.length;
console.log(`Received ${receivedLength} of ${contentLength}`);
updateProgressBar(receivedLength / contentLength);
}
const blob = new Blob(chunks);
const link = document.createElement('a');
link.href = URL.createObjectURL(blob);
link.download = 'file.ext';
link.click();
})
.catch(error => console.error('Error:', error));
}
function updateProgressBar(progress) {
const bar = document.getElementById('progressBar');
bar.style.width = `${progress * 100}%`;
}
function downloadFile(url) {
const xhr = new XMLHttpRequest();
xhr.open('GET', url, true);
xhr.responseType = 'blob';
xhr.onloadstart = function() {
// 初始化进度条
};
xhr.onprogress = function(event) {
if (event.lengthComputable) {
const percentComplete = (event.loaded / event.total) * 100;
updateProgressBar(percentComplete);
}
};
xhr.onload = function() {
if (this.status === 200) {
const blob = this.response;
const link = document.createElement('a');
link.href = URL.createObjectURL(blob);
link.download = 'file.ext';
link.click();
}
};
xhr.send();
}
function updateProgressBar(progress) {
const bar = document.getElementById('progressBar');
bar.style.width = `${progress}%`;
}
Content-Length
头,或者网络传输中的数据包丢失。Content-Length
存在且正确;对于不稳定网络,可以考虑实现重试机制。whatwg-fetch
来兼容不支持Fetch API的浏览器。通过以上方法,可以有效地实现和管理下载文件的进度条特效。
领取专属 10元无门槛券
手把手带您无忧上云