axios({
url: '下载接口URL',
method: 'post',
baseURL: process.env.VUE_APP_BASE_API,
params: params,
headers: { 'token': getToken() }
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].trim() === '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)
// 方法二:通过FileReader对象实现下载
const reader = new FileReader()
reader.readAsDataURL(res.data)
reader.onload = (e) => {
const a = document.createElement('a')
a.download = fileName
// console.log('e.target.result', e.target.result)
a.href = e.target.result
a.style.display = 'none'
document.body.appendChild(a)
a.click()
document.body.removeChild(a)
}
} else {
console.log('error', data)
}
})