在Web开发中,为HTTP请求添加进度条可以提升用户体验,尤其是在处理大文件上传或下载时。以下是实现这一功能的基础概念和相关步骤:
function uploadFile(file) {
var xhr = new XMLHttpRequest();
var progressBar = document.getElementById('progress-bar');
xhr.upload.addEventListener('progress', function(event) {
if (event.lengthComputable) {
var percentComplete = (event.loaded / event.total) * 100;
progressBar.value = percentComplete;
}
}, false);
xhr.open('POST', '/upload', true);
xhr.send(file);
}
async function uploadFile(file) {
const progressBar = document.getElementById('progress-bar');
const response = await fetch('/upload', {
method: 'POST',
body: file,
headers: {
'Content-Type': file.type
}
});
const reader = response.body.getReader();
const contentLength = +response.headers.get('Content-Length');
let receivedLength = 0;
while (true) {
const { done, value } = await reader.read();
if (done) break;
receivedLength += value.length;
progressBar.value = (receivedLength / contentLength) * 100;
}
}
progress
事件监听器已正确添加,并且在请求过程中能够触发。event.lengthComputable
为false
,表示无法计算总长度。Content-Length
头,或者使用其他方式估算进度。通过上述方法,可以为HTTP请求添加一个有效的进度条,从而提升用户交互体验。
领取专属 10元无门槛券
手把手带您无忧上云