使用axios.post(url,data,params)
向后臺請求excel流文件
/**
* 處理返回的excel文件流
*/
export function exportExcel(res,name='統(tǒng)計') {
const blob = new Blob([res.data]);
const fileName = name + '.xlsx';
const elink = document.createElement('a');
elink.download = fileName;
elink.style.display = 'none';
elink.href = URL.createObjectURL(blob);
document.body.appendChild(elink);
elink.click();
URL.revokeObjectURL(elink.href); // 釋放URL 對象
document.body.removeChild(elink);
}
export default {
methods:{
/**
* 導(dǎo)出
*/
downloadExcel(){
let data = {};
this.axios2.post('/testDownExcelUrl',data,{
responseType:'blob',
header:{
'Content-Type':'application/json;charset=UTF-8',
}
}).then(res => {
exportExcel(res,'我的賬單');
})
},
}
}
如果配置了axios響應(yīng)攔截器阁猜,改變了返回值結(jié)構(gòu)丸逸,需要判斷responseType == "blob"
來根據(jù)自己需要返回對應(yīng)的數(shù)據(jù)結(jié)構(gòu)。
// axios 相應(yīng)攔截器
axios.interceptors.response.use(
response => {
if (response.config.responseType == "blob") { //返回類型為流形式的文件
if (response.status === 200) {
return response
} else {
return Promise.reject(new Error('請求異常'));
}
} else {
let res = response.data
if (res.code === 1) {
return response.data
} else {
Message({
message: res.message,
type: "error",
duration: 5 * 1000
});
return Promise.reject(new Error(res.message||'請求異常'));
}
}
},
error => {
Message({
message: error.message,
type: "error",
duration: 5 * 1000
});
return Promise.reject(error)
}
);