前言
本文并不能直接复制到本地看效果,仅提供代码参考
1.使用axios的方式携带请求头token
2.设置响应的数据类型
responseType: "blob"
3.请求成功,返回二进制文件的数据回来
4.请求失败,返回json
5.示例代码
<template>
<div>
<el-button type="primary" size="small" :loading="btnLoading" @click="exportFile">导出</el-button>
</div>
</template>
<script>
import axios from "axios";
export default {
data() {
return {
btnLoading: false
};
},
methods: {
// responseType 响应类型
exportFile() {
this.btnLoading = true;
axios({
method: 'get',
url: '/api',
headers: {
token: '79faf82271944fe38c4f1d99be71bc9c'
},
responseType: "blob"
})
.then(res => {
this.btnLoading = false;
if (res.data.type) {
// 文件下载
const blob = new Blob([res.data], {
type: "application/vnd.ms-excel"
});
let link = document.createElement('a');
link.href = URL.createObjectURL(blob);
link.setAttribute('download', '导出文件.xlsx');
link.click();
link = null;
this.$message.success('导出成功');
} else {
// 返回json
this.$message.warning(res.data.msg);
}
})
.catch(err => {
this.btnLoading = false;
this.$message.error("下载失败");
});
}
}
};
</script>