vue前端实现下载进度
实现下载进度显示的方法
在Vue中实现下载进度显示,可以通过监听XMLHttpRequest或fetch的progress事件来获取下载进度数据。以下是具体实现方式:
使用XMLHttpRequest实现
XMLHttpRequest对象提供了progress事件,可以监听下载进度:

downloadFile(url) {
const xhr = new XMLHttpRequest();
xhr.open('GET', url, true);
xhr.responseType = 'blob';
xhr.addEventListener('progress', (event) => {
if (event.lengthComputable) {
const percentComplete = Math.round((event.loaded / event.total) * 100);
this.downloadProgress = percentComplete;
}
});
xhr.onload = () => {
if (xhr.status === 200) {
const blob = new Blob([xhr.response]);
const link = document.createElement('a');
link.href = window.URL.createObjectURL(blob);
link.download = 'filename.ext';
link.click();
}
};
xhr.send();
}
使用axios实现
axios也支持进度监听,可以通过onDownloadProgress配置项实现:

async downloadWithAxios(url) {
try {
const response = await axios({
url,
method: 'GET',
responseType: 'blob',
onDownloadProgress: (progressEvent) => {
const percentCompleted = Math.round(
(progressEvent.loaded * 100) / progressEvent.total
);
this.downloadProgress = percentCompleted;
}
});
const url = window.URL.createObjectURL(new Blob([response.data]));
const link = document.createElement('a');
link.href = url;
link.setAttribute('download', 'filename.ext');
document.body.appendChild(link);
link.click();
} catch (error) {
console.error('Download error:', error);
}
}
使用fetch API实现
fetch API本身不直接支持进度跟踪,但可以通过读取响应体的流来实现:
async fetchWithProgress(url) {
const response = await fetch(url);
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;
this.downloadProgress = Math.round((receivedLength / contentLength) * 100);
}
const blob = new Blob(chunks);
const downloadUrl = window.URL.createObjectURL(blob);
const link = document.createElement('a');
link.href = downloadUrl;
link.download = 'filename.ext';
link.click();
}
进度条UI实现
在Vue模板中可以这样显示进度:
<template>
<div>
<button @click="downloadFile">下载文件</button>
<div v-if="downloadProgress > 0">
<progress :value="downloadProgress" max="100"></progress>
<span>{{ downloadProgress }}%</span>
</div>
</div>
</template>
注意事项
- 确保服务器正确设置了Content-Length头部,否则无法计算进度百分比
- 对于大文件下载,考虑使用分块下载或断点续传技术
- 下载完成后及时释放创建的URL对象,避免内存泄漏
- 添加错误处理逻辑,处理网络中断等异常情况
以上方法可以根据具体需求选择使用,XMLHttpRequest和axios的实现方式相对简单,而fetch API的实现则更现代但代码量稍多。






