vue前端实现下载模板
Vue 前端实现下载模板的方法
使用 <a> 标签下载
在 Vue 模板中添加一个下载链接,通过 download 属性指定文件名:
<template>
<a href="/path/to/template.xlsx" download="template.xlsx">下载模板</a>
</template>
将模板文件放在 public 目录下,路径直接引用即可。
通过 Blob 对象动态下载
使用 axios 或 fetch 获取文件数据,转换为 Blob 对象并创建下载链接:
methods: {
downloadTemplate() {
axios.get('/api/download/template', { responseType: 'blob' })
.then(response => {
const url = window.URL.createObjectURL(new Blob([response.data]));
const link = document.createElement('a');
link.href = url;
link.setAttribute('download', 'template.xlsx');
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
});
}
}
使用第三方库 FileSaver.js
安装 file-saver 库:
npm install file-saver
在组件中使用:
import { saveAs } from 'file-saver';
methods: {
downloadTemplate() {
axios.get('/api/download/template', { responseType: 'blob' })
.then(response => {
saveAs(response.data, 'template.xlsx');
});
}
}
后端返回文件流时的处理
如果后端返回的是文件流,确保设置正确的响应头:

axios.get('/api/download/template', {
responseType: 'blob',
headers: {
'Content-Type': 'application/octet-stream'
}
}).then(response => {
// 处理下载逻辑
});
注意事项
- 确保文件路径或 API 接口正确。
- 跨域请求时,后端需配置 CORS 支持。
- 大文件下载时建议显示进度提示。
以上方法可根据实际需求选择,Blob 方式适合动态生成的文件,<a> 标签适合静态文件。






