上一篇文章使用fetch方法来下载Excel。但因为现在有的下载文件的接口,需要传很多参数。而fetch的get方法,只能将参数一个一个进行拼接,十分麻烦,所以将他改造成axios方法来进行下载。
使用fetch()获取响应头的content-disposition拿到文件名,下载Excel文件
老规矩,先上代码
exportExcel() {
const a = document.createElement('a')
this.$axios.request({
url: process.env.BASE_ACC_API + '/bok/export_account_balance/',
method: 'get',
params: this.popoverForm,
responseType: 'blob'
}).then(res => {
console.log('res', res)
// 切割出文件名
const fileNameEncode = res.headers['content-disposition'].split('filename=')[1]
// 解码
const fileName = decodeURIComponent(fileNameEncode)
console.log('fileName', fileName)
// 设置type类型
const blob = new Blob([res.data], {
type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet; application/octet-stream'
})
const fileUrl = window.URL.createObjectURL(blob)
a.href = fileUrl
console.log('url', fileUrl)
a.setAttribute('download', fileName)
a.style.display = 'none'
a.click()
a.remove()
})
}
这里要注意 配置里一定要加上 responseType: ‘blob’,
返回来的数据才是blob数据,否则下载下来的文件打不开。
最后可以自己将这段代码封装成一个函数,只暴露url和要传的参数,方便使用。