vue 实现文件下载
Vue 实现文件下载的方法
在 Vue 项目中实现文件下载可以通过多种方式完成,以下是几种常见的方法:
使用 <a> 标签下载
通过动态创建 <a> 标签并设置 download 属性实现文件下载。适用于已知文件 URL 的情况。
downloadFile(url, fileName) {
const link = document.createElement('a');
link.href = url;
link.download = fileName;
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
}
通过 Blob 对象下载
当需要下载后端返回的二进制流数据时,可以使用 Blob 对象。
downloadBlob(data, fileName, fileType) {
const blob = new Blob([data], { type: fileType });
const url = window.URL.createObjectURL(blob);
const link = document.createElement('a');
link.href = url;
link.download = fileName;
document.body.appendChild(link);
link.click();
window.URL.revokeObjectURL(url);
document.body.removeChild(link);
}
使用 axios 下载文件
结合 axios 请求后端接口获取文件数据后下载。
axios({
method: 'get',
url: '/api/download',
responseType: 'blob'
}).then(response => {
const url = window.URL.createObjectURL(new Blob([response.data]));
const link = document.createElement('a');
link.href = url;
link.download = 'file.pdf';
link.click();
});
使用 FileSaver.js 库
FileSaver.js 是一个专门用于客户端保存文件的 JavaScript 库,可以简化下载流程。
安装依赖:
npm install file-saver
使用示例:
import { saveAs } from 'file-saver';
// 保存文本
saveAs(new Blob(["Hello, world!"], {type: "text/plain;charset=utf-8"}), "hello world.txt");
// 保存图片
saveAs('https://example.com/image.png', 'image.png');
处理大文件下载
对于大文件下载,可以显示下载进度。
axios({
method: 'get',
url: '/api/large-file',
responseType: 'blob',
onDownloadProgress: progressEvent => {
const percentCompleted = Math.round((progressEvent.loaded * 100) / progressEvent.total);
console.log(percentCompleted + '% downloaded');
}
}).then(response => {
const url = window.URL.createObjectURL(new Blob([response.data]));
const link = document.createElement('a');
link.href = url;
link.download = 'large-file.zip';
link.click();
});
注意事项
- 确保服务器正确设置了响应头,特别是
Content-Disposition头 - 跨域请求需要服务器配置 CORS 头
- 某些浏览器可能对自动下载有限制
- 移动端设备可能需要特殊处理
以上方法可以根据具体需求选择使用,Blob 方式适合处理后端返回的二进制数据,而简单的文件下载可以直接使用 <a> 标签方式。







