需求:点击导出按钮,发送POST请求,下载Excel文件
首先,需要跟后端确认接口的Response Header设置了
设置完毕后,前端调用接口,把axios的responseType改为‘blob’
axios({
method: 'post',
url: 'xxxxxxx',
data: {},
responseType: 'blob'
}).then(res => {
let data = res
if (!data) {
return
}
let url = window.URL.createObjectURL(new Blob([data]))
let a = document.createElement('a')
a.style.display = 'none'
a.href = url
a.setAttribute('download','excel.xls')
document.body.appendChild(a)
a.click() //执行下载
window.URL.revokeObjectURL(a.href)
document.body.removeChild(a)
}).catch((error) => {
console.log(error)
})
然后点击下载,一切都是那么的顺利,文件下载成功了,忍不住高兴了一下
打开文件一看,凉凉~
后面发现,接口返回的数据response里面还有一层data,于是乎,把代码改为
axios({
method: 'post',
url: 'xxxxxxx',
data: {},
responseType: 'blob'
}).then(res => {
let data = res.data // 这里后端对文件流做了一层封装,将data指向res.data即可
if (!data) {
return
}
let url = window.URL.createObjectURL(new Blob([data]))
let a = document.createElement('a')
a.style.display = 'none'
a.href = url
a.setAttribute('download','excel.xls')
document.body.appendChild(a)
a.click() //执行下载
window.URL.revokeObjectURL(a.href) //释放url
document.body.removeChild(a) //释放标签
}).catch((error) => {
console.log(error)
})
最后,下载的Excel文件就正常了