项目需求
在项目中需要对pdf、word、excel等文档的下载
也就是获取文件的静态路径,下载到本地。
方案 :利用 axios 下载
具体实现
项目技术 Vue2 + element UI中实现
首先需要一个按钮来触发点击事件
<el-button type="primary" @click="download">下载文档</el-button>
在需要下载文档的页面引入 axios
import axios from 'axios';
将需要导出的文件放到 static 文件下
download(){
axios('static/file.pdf',{
responseType: 'blob', //重要代码
}).then(res =>{
const url = window.URL.createObjectURL(new Blob([res.data]));
const link = document.createElement('a');
link.href = url;
let fileName = "使用说明文档" //保存到本地的文件名称
link.setAttribute('download', fileName);
document.body.appendChild(link);
link.click();
}
}
项目技术 Vue3 + element UI中实现
与Vue2项目一样,需要按钮来触发事件
<el-button type="primary" @click="download">下载文档</el-button>
在需要下载文档的页面引入 axios
import axios from 'axios';
将需要导出的文件放到 public 文件下
实现下载代码一致
download(){
axios('static/file.pdf',{
responseType: 'blob', //重要代码
}).then(res =>{
const url = window.URL.createObjectURL(new Blob([res.data]));
const link = document.createElement('a');
link.href = url;
let fileName = "使用说明文档" //保存到本地的文件名称
link.setAttribute('download', fileName);
document.body.appendChild(link);
link.click();
}
}
注意
Vue2中的静态资源在 static。
Vue3中的静态资源则在 public。
文件存放错的话,会获取不到本地文件的。