后端提供的接口方法有Get和Post两种
文件流形式大概如下:
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/72def6da30afe76b7dd3ecf46b5c434c.png)
第一种Get方法,下载文件
不需要传参,代码如下:
<el-form-item>
<el-button
size="small"
v-if="checkBtnAuth('user-select')"
type="success"
icon="el-icon-download"
@click="downloadExcel"
>下载模板</el-button
></el-form-item
>
<el-form-item>
downloadExcel() {
window.location.href = `${location.origin}/api/check/downloadTemplate`;
},
第二种Post,需要传参导出Excel
<el-form-item
><el-button type="success" size="small" @click="ExportFile($event)"
>导出Excel文件<i
class="el-icon-upload2 el-icon--right"
></i></el-button
></el-form-item>
ExportFile() {
axios
.request({
url: "/api/checkStat/exportToExcel",//请求地址
method: "post", //post方法
data: this.formInline, //传参
headers: { //请求头
"Content-Type": "application/json; charset=UTF-8",
},
responseType: "blob", //在请求中加上这一行,特别重要
})
.then((res) => {
const blob = new Blob([res.data], {
type: "application/vnd.ms-excel;charset=UTF-8",
});// 创建一个类文件对象:Blob对象表示一个不可变的、原始数据的类文件对象
const downloadElement = document.createElement("a"); //创建a标签
const href = window.URL.createObjectURL(blob); // 创建下载的链接
var temp = res.headers["content-disposition"];
var fileName = decodeURIComponent(temp.split("filename=")[1]); // 中文需要转码 (前端乱码)
var name = fileName.split(";")[0]; //切割成文件名
downloadElement.href = href; //下载地址
downloadElement.download = name; // 下载后文件名
document.body.appendChild(downloadElement);
downloadElement.click(); // 点击下载
document.body.removeChild(downloadElement); // 下载完成移除元素
window.URL.revokeObjectURL(href); // 释放blob对象
});
},
注意事项
1、文件后缀要写对 .xls或 .xlsx
2、根据后端返回的数据处理文件名称
var fileName = decodeURIComponent(temp.split("filename=")[1]); // 中文需要转码 (前端乱码)
var name = fileName.split(";")[0]; //切割成文件名