转载:https://www.cnblogs.com/coconutGirl/p/12605562.html
前端下载EXCEL文件,后端返回文件流的处理
axios({
url: '下载接口URL',
method: 'post',
data: {},
responseType: 'blob'
}).then((res) => {
// data就是接口返回的文件流
let data = res.data
if (data) {
let attrs = res.headers['content-disposition'].split(';')
// 获取文件名
let fileName = ''
// 不用管fileName在第几个位置,只要=前面是fileName,就取=后面的值
for (let i = 0, l = attrs.length; i < l; i++) {
let temp = attrs[i].split('=')
if (temp.length > 1 && temp[0] === 'fileName') {
fileName = temp[1]
break
}
}
fileName = decodeURIComponent(fileName)
// 获取数据类型
let type = res.headers['content-type'].split(';')[0]
let blob = new Blob([res.data], { type: type })
const a = document.createElement('a')
// 创建URL
const blobUrl = window.URL.createObjectURL(blob)
a.download = fileName
a.href = blobUrl
document.body.appendChild(a)
// 下载文件
a.click()
// 释放内存
URL.revokeObjectURL(blobUrl)
document.body.removeChild(a)
} else {
console.log('error', data)
}
})
**
再强调下,一定一定不要忘了responseType: ‘blob’
**
补充:还有一种
daochu() {
this.loadingAll=true
taskExport(this.params).then((res) => {
this.loadingAll=false
this.getOutExcel('任务统计.xlsx', res);
});
},
getOutExcel(fileName, res) {
let blob = new Blob([res], { type: 'application/x-xls' });
if (window.navigator.msSaveOrOpenBlob) {
//兼容 IE & EDGE
navigator.msSaveBlob(blob, fileName);
} else {
var link = document.createElement('a');
// 兼容不同浏览器的URL对象
const url = window.URL || window.webkitURL || window.moxURL;
// 创建下载链接
link.href = url.createObjectURL(blob);
//命名下载名称
link.download = fileName;
//点击触发下载
link.click();
//下载完成进行释放
url.revokeObjectURL(link.href);
}
},