之前使用axios下載一直是好好的,知道產品提出,下載的錯誤信息需要提示出來而不是顯示在下載文件裏面。
在網上搜索良久,也沒有答案沒辦法,只能去這裏找https://developer.mozilla.org/zh-CN/docs/Web/API/Blob/text查找文檔。
廢話少數,直接把代碼貼出來
Vue.axios({
method: 'post',
url: param.url,
data: param.body,
headers: param.headers || {responseType: 'blob'},
responseType: 'blob'
}).then(async res => {
// 導出錯誤模板提示
if (res.data.type === 'application/json') {
const text = await res.data.text()
const jsonText = await JSON.parse(text)
resolve(jsonText)
} else {
const success = {
status: 200
}
let fileName = ``
const content = res.data
if (res.headers) {
fileName = decodeURI(decodeURI(res.headers['content-disposition'])).split('filename=')[1]
}
if (!fileName) {
fileName = `${Vue.$moment().format('YYYYMMDDhhmm')}.xls`
}
const blob = new Blob([content], {
type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=UTF-8'
})
if ('download' in document.createElement('a')) {
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)
document.body.removeChild(elink)
} else {
navigator.msSaveBlob(blob, fileName)
}
resolve(success)
}
起作用的就是這段代碼。
把返回來的流文件解析爲json。
正確時直接下載模板。錯誤時判斷返回類型,轉換json。
注意是一個異步方法 使用 async await處理就好