vue实现流下载
Vue 实现流下载
在 Vue 中实现流下载通常涉及从后端获取二进制流数据,并将其转换为可下载的文件。以下是实现方法:
使用 Axios 获取流数据
通过 Axios 请求后端接口,设置 responseType 为 'blob' 以接收二进制流数据:
axios.get('/api/download', {
responseType: 'blob'
}).then(response => {
const blob = new Blob([response.data]);
const url = window.URL.createObjectURL(blob);
const link = document.createElement('a');
link.href = url;
link.download = 'filename.ext'; // 设置文件名
link.click();
window.URL.revokeObjectURL(url); // 释放内存
});
处理大文件分块下载
对于大文件,可以结合后端的分块传输实现流式下载:
axios.get('/api/large-file', {
responseType: 'blob',
onDownloadProgress: (progressEvent) => {
const percent = Math.round((progressEvent.loaded * 100) / progressEvent.total);
console.log(`下载进度: ${percent}%`);
}
}).then(response => {
// 处理下载完成逻辑
});
后端配合要求
后端需要正确设置响应头以支持流下载:
Content-Type: application/octet-streamContent-Disposition: attachment; filename="filename.ext"
浏览器兼容性处理
对于不支持 Blob 的旧浏览器,可使用 FileSaver.js 库:
import { saveAs } from 'file-saver';
// 在 Axios 回调中使用
saveAs(blob, 'filename.ext');
进度显示优化
在 Vue 组件中显示下载进度:
data() {
return {
downloadProgress: 0
}
},
methods: {
downloadFile() {
axios.get('/api/file', {
responseType: 'blob',
onDownloadProgress: (progressEvent) => {
this.downloadProgress = Math.round(
(progressEvent.loaded * 100) / progressEvent.total
);
}
}).then(response => {
// 处理下载
});
}
}
错误处理
添加适当的错误处理逻辑:

axios.get('/api/download', {
responseType: 'blob'
}).catch(error => {
console.error('下载失败:', error);
// 显示错误提示
});
以上方法实现了 Vue 中的流下载功能,支持进度显示和错误处理,适用于各种文件类型的下载需求。






