文件流轉換
一般用於axios設置接收文件流設置時responseType: 'blob'當接口報錯時,前端因已設置responseType: 'blob'無法再接收json格式數據,會把json格式數據轉為blob格式,而到了這里攔截器已無法識別blob進而無法對blob數據進行攔截,這個時候就需要前端將數據blob格式進行轉換成正常的json的數據,這會導致前端無法顯示報錯信息
/**
* 文件流轉換 主要代碼塊,可自定義下載文件名稱
* @param {} data
*/
export function download(data, titName) {
var reader = new FileReader()
reader.readAsText(data, 'utf-8')
reader.onload = function() {
try {
const newRes = JSON.parse(reader.result) // 獲取blob數據轉換為json后的數據,即后台返回的原始數據
if (!newRes.success) {
if (newRes.code === '407') {
MessageBox.confirm(newRes.message, i18n.t('tips.confirmlogout'), {
confirmButtonText: i18n.t('btn.loginagain'),
cancelButtonText: i18n.t('btn.cancel'),
type: 'warning',
duration: 0,
showClose: true
}).then(() => {
store.dispatch('user/resetToken').then(() => {
location.reload()
})
Promise.reject()
}).catch(err => {
return Promise.reject(err)
})
} else {
Notification.error({
title: 'Server Error',
message: newRes.message,
duration: 0,
showClose: true
})
}
}
} catch (err) {
if (!data) {
return
}
const content = data
const blob = new Blob([content], { type: 'application/vnd.ms-excel' })
const fileName = titName || 'EXCEl.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)
}
}
}
}