vue实现模板下载
Vue 实现模板下载的方法
使用 Blob 对象和 URL.createObjectURL
创建一个 Blob 对象,包含模板内容,生成下载链接。这种方法适用于动态生成的内容或简单的文本模板。
downloadTemplate() {
const content = '模板内容'; // 替换为实际模板内容
const blob = new Blob([content], { type: 'text/plain' });
const url = URL.createObjectURL(blob);
const link = document.createElement('a');
link.href = url;
link.download = 'template.txt'; // 设置文件名
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
URL.revokeObjectURL(url);
}
使用 axios 下载服务器上的模板文件
如果模板文件存储在服务器上,可以通过 axios 请求文件并触发下载。

import axios from 'axios';
downloadTemplate() {
axios({
url: '/api/template/download', // 替换为实际接口地址
method: 'GET',
responseType: 'blob'
}).then(response => {
const url = URL.createObjectURL(new Blob([response.data]));
const link = document.createElement('a');
link.href = url;
link.download = 'template.xlsx'; // 设置文件名
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
URL.revokeObjectURL(url);
});
}
使用静态文件直接下载
对于存储在 public 目录下的静态模板文件,可以直接通过 a 标签下载。

<template>
<a href="/templates/template.docx" download>下载模板</a>
</template>
使用第三方库 file-saver
安装 file-saver 库可以简化下载流程,适用于更复杂的下载需求。
npm install file-saver --save
import { saveAs } from 'file-saver';
downloadTemplate() {
const content = '模板内容';
const blob = new Blob([content], { type: 'text/plain' });
saveAs(blob, 'template.txt');
}
处理大文件下载
对于大文件,可以使用分片下载或显示下载进度。
downloadLargeTemplate() {
axios({
url: '/api/template/large',
method: 'GET',
responseType: 'blob',
onDownloadProgress: progressEvent => {
const percent = Math.round((progressEvent.loaded / progressEvent.total) * 100);
console.log(`下载进度: ${percent}%`);
}
}).then(response => {
saveAs(new Blob([response.data]), 'large_template.zip');
});
}
注意事项
- 确保服务器正确设置响应头,特别是
Content-Disposition和Content-Type。 - 跨域下载需要服务器支持 CORS。
- 对于敏感文件,应添加权限验证。
- 下载完成后及时释放内存,调用
URL.revokeObjectURL()。






