背景
axios 是個輕量級的 http 客戶端,vue項(xiàng)目中使用非常普遍,現(xiàn)在需要對接一個excel下載接口,發(fā)現(xiàn) axios 無法直接直接下載下來,也就是說用 axios 請求,返回的結(jié)果是二進(jìn)制文件,但是瀏覽器沒有直接下載下來,下面是解決的方案的代碼片段。當(dāng)然也適用于其他二進(jìn)制文件下載。
詳細(xì)可查看 Axios 中文文檔
應(yīng)用
exportData () {
const form = this.getSearchForm() // 要發(fā)送到后臺的數(shù)據(jù)
axios({ // 用axios發(fā)送post請求
method: 'post',
url: '/user/12345', // 請求地址
data: form, // 參數(shù)
responseType: 'blob' // 表明返回服務(wù)器返回的數(shù)據(jù)類型
})
.then((res) => { // 處理返回的文件流
const content = res
const blob = new Blob([content])
const fileName = '測試表格123.xls'
if ('download' in document.createElement('a')) { // 非IE下載
const elink = document.createElement('a')
elink.download = fileName
elink.style.display = 'none'
elink.href = URL.createObjectURL(blob)
document.body.appendChild(elink)
elink.click()
URL.revokeObjectURL(elink.href) // 釋放URL 對象
document.body.removeChild(elink)
} else { // IE10+下載
navigator.msSaveBlob(blob, fileName)
}
})
}
這里用了Blob對象,上面的寫法就是用從服務(wù)器接收到的文件流(content-type:application/octet-stream)創(chuàng)建了一個blob對象,并使用該blob 創(chuàng)建一個指向類型數(shù)組的URL,將該url作為a標(biāo)簽的鏈接目標(biāo),然后去觸發(fā)a標(biāo)簽的點(diǎn)擊事件從而實(shí)現(xiàn)表格下載。
get請求也可以實(shí)現(xiàn),后續(xù)增加。。。