方案一
在請求下載的時候,為了解決亂碼問題,我們都會給 XHR 的 responseType 指定為 blob 或者 arraybuffer。但是在實際下載的過程中,后端返回的不一定是二進制流數(shù)據(jù),也有可能是 json 格式的錯誤信息,比如導出數(shù)據(jù)量過大,需要縮小范圍,或者查詢結果出錯等錯誤信息,需要在前端頁面以 toast 的方式提示給使用者。
假如有以下代碼
// 下載
async function downloadFn(params) {
const result = await axios.get(
url,
{
params,
responseType: 'blob'
}
)
downloadBlob(result)
}
// 通用的下載函數(shù)
function downloadBlob(response, fileName) {
const blob = new Blob([response.data], { type: 'application/octet-stream' })
if (fileName === undefined) {
fileName = decodeURIComponent(
response.headers['content-disposition'].split(';')[1].split('=')[1]
)
}
if (navigator.msSaveBlob) {
navigator.msSaveBlob(blob, fileName)
} else {
const linkElement = document.createElement('a')
linkElement.download = fileName
linkElement.style.display = 'none'
linkElement.href = URL.createObjectURL(blob)
document.body.appendChild(linkElement)
const clickEvent = document.createEvent('MouseEvents')
clickEvent.initEvent('click', false, false)
linkElement.dispatchEvent(clickEvent)
URL.revokeObjectURL(linkElement.href) // 釋放URL 對象
document.body.removeChild(linkElement)
}
}
那么如果后臺沒有返回二進制流數(shù)據(jù),而是返回了 JSON 數(shù)據(jù)格式,那么我們捕捉到的錯誤信息是 downloadBlob 函數(shù)中的response.headers['content-disposition']為undefined,undefined是不能進行 split 方法的。
為了解決這個問題,新增了一個方法
// 記住,這個地方傳入的是response,而不是請求拿到的response.data
function judgeErrorByResponseType(response) {
return new Promise((resolve, reject) => {
if (response.headers['content-type'].includes('json')) {
// 此處拿到的data才是blob
const { data } = response
const reader = new FileReader()
reader.onload = () => {
const { result } = reader
const errorInfos = JSON.parse(result)
const { msg } = errorInfos
reject(new Error(msg))
}
reader.onerror = err => {
reject(err)
}
reader.readAsText(data)
} else {
resolve(response)
}
})
}
當然,我前端在這個方法的編寫的時候對后臺也是有要求的,就是要他準確的返回 content-type。如果是二進制流數(shù)據(jù),content-type就必須是application/octet-stream,如果是 JSON 數(shù)據(jù)格式的錯誤信息,就必須得返回application/json。因為本次實踐中我發(fā)現(xiàn)了后臺有一些不規(guī)范的地方,就是不管返回的是什么數(shù)據(jù)類型,headers 永遠是Content-Type: application/json;charset=UTF-8。

上面的judgeErrorByResponseType方法非常簡單,其實只是做一次記錄,只要對 fileReader 有了解相信都可以寫出來,只是方便以后用到懶得再寫一次。當然在使用過程中,只需要在下載之前做一個判斷即可
async function downloadFn(params) {
const result = await axios.get(
url,
{
params,
responseType: 'blob'
}
)
const response = await judgeErrorByResponseType(result)
downloadBlob(response)
}
方案二
導出文件,responseType設置了blob,實際返回了JSON格式的錯誤信息的處理方式
需求:導出文件
問題描述:由于后臺直接返回的文件流,在請求下載的方法中將XHR 的 responseType 指定為 blob 或者 arraybuffer。但并不是每次的操作都是成功的,所以在接口錯誤時后臺返回的就是不是二進制流格式了。因此這里需要獲取到后臺反饋的錯誤信息進行用戶提示。
這時后臺返回的數(shù)據(jù)類型就是這樣的:

而接口返回的是json的數(shù)據(jù)信息{“msg”: "導出失敗", code: 1007}
解決代碼示例:
getFiles(_path, query) {
axios({
method: 'get', // 請求方式
headers: {
'Content-Type': 'application/octet-stream',
'token': store.getters.token
},
url: _path, // 請求路徑
params: query,
responseType: 'blob'
}).then(res => {
const data = res.data;
if (res.data.type == 'application/json') { // json信息展示
this.handlerResponseError(data);
} else {
// 下載文件流
const filename = this.getCaption(res.headers['content-disposition']);
const blob = new Blob([res.data], {
type: 'application/octet-stream'
});
const objectUrl = URL.createObjectURL(blob);
const link = document.createElement('a');
link.href = objectUrl;
link.setAttribute('download', filename);
document.body.appendChild(link);
link.click();// 點擊
document.body.removeChild(link); // 下載完成移除元素
window.URL.revokeObjectURL(URL); // 釋放掉blob對象
}
}).catch((err) => {
console.log(err, 'err');
});
},
handlerResponseError(data) {
const _this = this;
const fileReader = new FileReader();
fileReader.onload = function() {
try {
const jsonData = JSON.parse(fileReader.result); // 說明是普通對象數(shù)據(jù),后臺轉換失敗
console.log('后臺返回的信息',jsonData.msg);
// dosomething……
} catch (err) { // 解析成對象失敗,說明是正常的文件流
console.log('success...');
}
};
fileReader.readAsText(data);
},