axios 请求导出excel文件
调取后端接口导出excel文件,分别用get/post请求获取调接口
get请求导出文件
// 导出
exportFile() {
//后台接口地址
var userBase =`${this.apiUrl}/downFile`;
//传递参数
var url = `${userBase}?uid=${this.orderForm.uid}`;
var linkElement = document.createElement("a");
try {
linkElement.setAttribute("href", url);
var clickEvent = new MouseEvent("click", {
view: window,
bubbles: true,
cancelable: false,
});
linkElement.dispatchEvent(clickEvent);
} catch (ex) {
console.log(ex);
}
},
弊端:此方法较为简单,但是当请求参数较多,数据较多时,可能会无法使用,这时候还是需要考虑post的方式
post请求导出文件
exportFile() {
//{ responseType: 'blob' }这句很重要,防止导出文件乱码
//nameForm为参数
this.axios.post('/downFile',nameForm,{ responseType: 'blob' })
.then((res)=>{
const url = window.URL.createObjectURL(new Blob([res.data]))
const link = document.createElement('a')
link.href = url
link.setAttribute('download', '列表导出.xls')
document.body.appendChild(link)
link.click()
})
}