后端返回的是文件流,前端一般會用blob處理,最重要的一步是在請求里要標明:responseType:'blob',將返回的文件流轉為blob
axios({
url: '下載接口URL',
method: 'post',
responseType: 'blob'
}).then((res) => {
// data就是接口返回的文件流
let data = res.data
if (data) {
// 處理文件名
let fileName = ''
let attrs = res.headers['content-disposition'].split(';')
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]
// type就是文件的mime類型,一般接口會返回。csv文件的mime一般采用text/csv
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)
}
})