1、需求描述
axios 發送請求。但是在使用 axios 實現下載功能時,往往會出現以下問題。
當前端直接使用 axios 去請求下載文件的 api 接口時,狀態碼返回200,但是獲取的數據卻是一堆亂碼,效果如下:
2、問題分析
下載其實是瀏覽器的內置事件,瀏覽器的 GET請求(frame、a)、 POST請求(form)具有如下特點:
- response 會交由瀏覽器處理;
- response 內容可以爲二進制文件、字符串等。
但是AJAX請求不一樣:
- response 會交由 Javascript 處理;
- response 內容只能接收字符串才能繼續處理。
因此,AJAX本身無法觸發瀏覽器的下載功能。
3、解決方案
要在 axios 的 config 配置 responseType: ‘blob’ (非常關鍵),服務端讀取文件,以 content-type: ‘application/octet-stream’ 的格式返回前端,前端接收到數據後使用 Blob 來接收數據,並且創建a標籤進行下載。
一個對象的類型取決於 responseType 的值,當值爲 “blob”時表示 response 是一個包含二進制數據的 Blob 對象。
在使用 axios 發起請求前,首先了解一下 responseType 這個屬性是如何在 axios 中使用的。以 axios 最常用的 get 和 post 請求爲例,這兩種請求方式在傳遞參數的時候也是不同的:
在get請求當中,config 是第二個參數,而到了 post 裏 config 變成了第三個參數,這是傳遞 responseType 第一個需要注意的地方。
4、代碼實現
後端實現以 express 爲例:
// 這裏以express舉例
const fs = require('fs')
const express = require('express')
const bodyParser = require('body-parser')
const app = express()
app.use(bodyParser.urlencoded({extended: false}))
app.use(bodyParser.json())
// 以post提交舉例
app.post('/info/download', function(req, res) {
const filePath = './myfile/test.zip'
const fileName = 'test.zip'
res.set({
'content-type': 'application/octet-stream',
'content-disposition': 'attachment;filename=' + encodeURI(fileName)
})
fs.createReadStream(filePath).pipe(res)
})
app.listen(3000)
前端在使用 axios 請求下載文件 api 接口時,一定要區分不同請求方法的使用,語法如下:
// axios設置reponseType的方式應該類似下面
const url = '/info/download'
// get、delete、head 等請求
axios.get(url, {params: {}, responseType: 'blob'})
.then((res) => {})
.catch((err) => {})
// post、put、patch 等請求
axios.post(url, {...params}, {responseType: 'blob'})
.then((res) => {})
.catch((err) => {})
前端解析數據流,主要使用 Blob 對象來進行接收,示例代碼如下:
// 以之前的post請求舉例
axios.post(url, {...someData}, {responseType: 'blob'})
.then((res) => {
const { data, headers } = res
const fileName = headers['content-disposition'].replace(/\w+;filename=(.*)/, '$1')
// 此處當返回json文件時需要先對data進行JSON.stringify處理,其他類型文件不用做處理
//const blob = new Blob([JSON.stringify(data)], ...)
const blob = new Blob([data], {type: headers['content-type']})
let dom = document.createElement('a')
let url = window.URL.createObjectURL(blob)
dom.href = url
dom.download = decodeURI(fileName)
dom.style.display = 'none'
document.body.appendChild(dom)
dom.click()
dom.parentNode.removeChild(dom)
window.URL.revokeObjectURL(url)
}).catch((err) => {})
例:
const handleOnSearchExport = () => {
console.log("handleOnSearchExport: ");
axiosInstance.post(
"/chanpush/orderpush/searchExport",
{"pushDate": queryPushDate.value},
{headers: {
'Content-Type': 'application/json',},
responseType: 'blob',
}).then((res)=>{
loading.value = false;
const { data, headers } = res
const fileName = headers['content-disposition'].replace(/\w+;filename=(.*)/, '$1')
const blob = new Blob([data], {type: headers['content-type']})
let dom = document.createElement('a')
let url = window.URL.createObjectURL(blob)
dom.href = url
dom.download = decodeURI(fileName)
dom.style.display = 'none'
document.body.appendChild(dom)
dom.click()
dom.parentNode.removeChild(dom)
window.URL.revokeObjectURL(url)
}).catch((err,res)=>{
loading.value = false;
})
}
如果後臺返回的流文件是一張圖片的話,前端需要將這張圖片直接展示出來,例如登錄時的圖片驗證碼,示例代碼如下:
axios.post(url, {...someData}, {responseType: 'blob'})
.then((res) => {
const { data } = res
const reader = new FileReader()
reader.readAsDataURL(data)
reader.onload = (ev) => {
const img = new Image()
img.src = ev.target.result
document.body.appendChild(img)
}
}).catch((err) => {})