vue前端实现文件下载
使用 Blob 对象和 URL.createObjectURL
通过创建 Blob 对象并生成临时 URL 实现文件下载。适用于后端返回文件流或前端生成文件的场景。
// 假设 response 是后端返回的文件流
const blob = new Blob([response.data], { type: 'application/octet-stream' });
const url = window.URL.createObjectURL(blob);
const link = document.createElement('a');
link.href = url;
link.download = 'filename.ext'; // 设置下载文件名
link.click();
window.URL.revokeObjectURL(url); // 释放内存
直接使用 a 标签下载
适用于已知文件 URL 且服务器允许直接下载的情况。
<a href="/path/to/file.ext" download="custom-filename.ext">下载文件</a>
处理跨域文件下载
当文件位于不同域名时,可能需要后端配合设置 CORS 或通过代理下载。
axios.get('/api/download', {
responseType: 'blob',
headers: {
'Authorization': 'Bearer your_token'
}
}).then(response => {
const contentDisposition = response.headers['content-disposition'];
const filename = contentDisposition.split('filename=')[1];
const blob = new Blob([response.data]);
// 后续步骤同第一种方法
});
大文件分片下载
对于大文件下载,可以显示下载进度并支持暂停续传。
const downloadFile = async (url, fileName) => {
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;
console.log(`下载进度: ${(receivedLength/contentLength*100).toFixed(2)}%`);
}
const blob = new Blob(chunks);
// 后续下载步骤
};
前端生成文件并下载
适用于需要在前端动态生成文件内容的场景。
const content = '文件内容';
const blob = new Blob([content], {type: 'text/plain'});
// 后续下载步骤同第一种方法
注意事项
- 确保服务器正确设置了 Content-Disposition 响应头
- 处理可能的错误情况,如网络中断或权限问题
- 移动端可能需要特殊处理,某些浏览器对下载限制较多
- 考虑添加下载进度提示和完成通知
- 对于敏感文件,应通过授权验证后再允许下载







