vue网页批量下载实现
Vue 网页批量下载实现方法
使用 axios 和 Blob 对象实现批量下载
通过 axios 请求文件数据,结合 Blob 对象和 URL.createObjectURL 生成下载链接。适用于后端返回文件流的场景。

import axios from 'axios';
function downloadFile(url, fileName) {
axios({
url,
method: 'GET',
responseType: 'blob',
}).then((response) => {
const blob = new Blob([response.data]);
const downloadUrl = window.URL.createObjectURL(blob);
const link = document.createElement('a');
link.href = downloadUrl;
link.setAttribute('download', fileName);
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
});
}
// 批量调用示例
const files = [
{ url: 'http://example.com/file1.pdf', name: 'file1.pdf' },
{ url: 'http://example.com/file2.pdf', name: 'file2.pdf' },
];
files.forEach(file => downloadFile(file.url, file.name));
使用 Promise.all 实现并发下载
通过 Promise.all 管理多个下载任务的并发执行,确保所有文件下载完成后触发回调。

function batchDownload(files) {
const downloadPromises = files.map(file =>
axios.get(file.url, { 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 = file.name;
link.click();
window.URL.revokeObjectURL(url);
})
);
return Promise.all(downloadPromises);
}
使用 FileSaver.js 库简化操作
通过第三方库 FileSaver.js 简化 Blob 文件保存过程,避免手动处理 DOM 操作。
import { saveAs } from 'file-saver';
function downloadWithFileSaver(url, fileName) {
axios.get(url, { responseType: 'blob' })
.then(response => {
saveAs(response.data, fileName);
});
}
处理后端返回的压缩包
若后端支持批量打包下载,直接请求压缩包地址即可减少前端压力。
function downloadZip(files) {
// 假设后端接口接收文件ID列表并返回ZIP
axios.post('/api/download-zip', { fileIds: files.map(f => f.id) }, {
responseType: 'blob'
}).then(response => {
saveAs(response.data, 'batch_files.zip');
});
}
注意事项
- 跨域问题:确保文件服务器配置了 CORS 允许当前域名访问。
- 性能优化:大量文件下载时建议分批次处理,避免浏览器卡顿。
- 错误处理:添加
catch块处理网络请求或文件生成的异常。
适用场景对比
| 方法 | 适用场景 | 优点 | 缺点 |
|---|---|---|---|
Blob + axios |
单文件或少量文件 | 无需依赖库 | 需手动处理DOM |
Promise.all |
并发下载多个小文件 | 并行效率高 | 可能触发浏览器并发限制 |
FileSaver.js |
简化Blob保存流程 | 代码简洁 | 需引入第三方库 |
| 后端打包下载 | 大量文件或大体积文件 | 减少前端性能压力 | 依赖后端支持 |






