1. 須將axios 配置中的responseType
設置為arraybuffer
,這樣就不會讓表格出現亂碼現象;
2. 如果要動態設置文件名則需要讓后台將名字設置到響應頭中,否則將是一個亂碼的文件名;
3. 然后通過<a></a>
標簽的特性來自動點擊下載文件;
4. 如果要兼容IE則需要利用navigator.msSaveOrOpenBlob
方法;
5. 兼容Firefox 須將<a></a>
標簽添加到body
中,最后再移除<a></a>
標簽
例子:
// axios config
config = {
responseType: 'arraybuffer'
}
// 返回數據處理
getUserInfoExport(data).then(({data,headers}) => {
let blob = new Blob([data], { type: 'application/vnd.ms-excel' }) // 將服務端返回的文件流(二進制)excel文件轉化為blob
let fileName = headers.filename
if (window.navigator && window.navigator.msSaveOrOpenBlob) { // IE
window.navigator.msSaveOrOpenBlob(blob, fileName)
} else {
let objectUrl = (window.URL || window.webkitURL).createObjectURL(blob)
let downFile = document.createElement('a')
downFile.style.display = 'none'
downFile.href = objectUrl
downFile.download = fileName // 下載后文件名
document.body.appendChild(downFile)
downFile.click()
document.body.removeChild(downFile) // 下載完成移除元素
// window.location.href = objectUrl
window.URL.revokeObjectURL(objectUrl) // 只要映射存在,Blob就不能進行垃圾回收,因此一旦不再需要引用,就必須小心撤銷URL,釋放掉blob對象。
}
})