1.封装请求
export function filePost(url, params, config) {
let userAuth = JSON.parse(sessionStorage.getItem("userAuth"));
return new Promise((resolve, reject) => {
axios.create({
baseURL: baseUrl,
timeout: 15000,
headers: {
"Content-Type": "application/json-patch+json",
"Authorization": userAuth.token_type + " " + userAuth.access_token,
},
responseType: "arraybuffer" //必须设置,不然导出的文件无法打开
})
.post(url, params, config)
.then(res => {
resolve(res);
})
.catch(err => {
reject(err);
});
});
}
- 调用函数并处理返回的文件流对象
在这里插入代码片
filePost("/TAreaReport/Export", data)
.then(res => {
//res.data: 文件流数组
const url = window.URL.createObjectURL(new Blob([res.data], {type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"}));
const link = document.createElement('a');
link.style.display = 'none';
link.href = url;
link.download = '文件名.xlsx';
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
this.timer = setTimeout(()=>{
this.$message.success('导出成功');
}, 3000)
})
.catch(() => {
this.$message({
type: "error",
message: '导出失败'
});
});