vue实现文件下载
使用 a 标签下载文件
通过动态创建 a 标签并触发点击事件实现文件下载。适用于直接下载服务器上的静态文件或 Blob 数据。
downloadFile(url, fileName) {
const link = document.createElement('a');
link.href = url;
link.download = fileName || 'file';
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
}
参数说明
url: 文件地址(需确保同源或支持 CORS)。fileName: 可选,下载时保存的文件名。
通过 Blob 下载后端返回的文件流
适用于后端返回二进制流(如 Excel、PDF 等)的情况。

downloadBlob(response, fileName) {
const blob = new Blob([response.data]);
const url = window.URL.createObjectURL(blob);
const link = document.createElement('a');
link.href = url;
link.download = fileName || 'file';
link.click();
window.URL.revokeObjectURL(url); // 释放内存
}
参数说明
response: 后端返回的响应对象(需确保response.data是二进制数据)。fileName: 可选,指定下载文件名。
使用 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();
});
注意事项
- 后端需设置正确的响应头(如
Content-Disposition: attachment)。 - 若需传递参数(如 ID),可通过
params或data字段添加。
处理浏览器兼容性
部分浏览器可能不支持 download 属性,需降级处理:
if (!link.download) {
// 降级方案:在新窗口打开文件
window.open(url, '_blank');
}
安全限制
- 跨域限制:非同源文件需服务器配置 CORS。
- 用户触发:部分浏览器要求下载操作必须由用户点击事件触发(如按钮点击)。
通过以上方法,可灵活实现 Vue 中的文件下载功能。






