最近项目上遇到前端获取后端传过来的文件流,导出Excel表格的问题,记录一下。
需要注意点:
1.responseType: 'blob',(指定类型参数一定要加)
2.headers (携带token,看项目需要,我这里需要加上才能正常访问后端接口i)
源码如下:
async exportExcel() {
try {
const requestData = {
...this.formInline,
merchantCode: '',
groupName: '',
orderBy: '',
current: '',
size: ''
};
requestData.current = this.table.currentPage;
requestData.size = this.table.pageSize;
requestData.merchantCode = this.merchantCode == '' ? this.userInfo.username : this.merchantCode;
const response = await axios.post(process.env.VUE_APP_BASE_API + '/haoxian/list/export', requestData, {
responseType: 'blob',
headers: { token: this.token }
});
console.log('exportExcel', response);
const url = window.URL.createObjectURL(new Blob([response.data]));
const link = document.createElement('a');
link.href = url;
link.setAttribute('download', '号显管理短链查询结果表.xlsx');
document.body.appendChild(link);
link.click();
document.removeChild(link);
} catch (error) {
console.log('导出失败', error);
}
}