有的时候,我们在axios请求处理的时候,需要处理对应的可能出现的报错信息,这个时候直接返回的response是不能直接反映出错误信息的.
所以这个时候,我们需要进行转化,转化代码如下:
这一段是转化并且在报错时抛出错误信息,如果没有报错,就将文件下载下来
// 下载文件的保存
handleDownloadData(param, url, blom) {
axios({
method: "post",
url: url,
data: param,
responseType: "blob",
}).then((res) => {
{
let typeCount = {
type: "application/octet-stream",
};
let _me=this;
let blob = new Blob([res.data],typeCount);
if (res.data.type != typeCount.type) {
// 说明是普通对象数据,后台转换失败
const fileReader = new FileReader()
fileReader.readAsText(blob,'utf-8')
fileReader.onload = function () {
let msg=JSON.parse(fileReader.result).errors.message;
return _me.$message.error(msg);
}
}
let fileName = res.headers["content-disposition"]
.split("filename=")
.pop();
fileName = decodeURI(fileName);
let url = window.URL.createObjectURL(blob);
let link = document.createElement("a");
link.style.display = "none";
link.href = url;
link.setAttribute("download", fileName);
document.body.appendChild(link);
link.click();
this.loading = false;
document.body.removeChild(link);
this.isloading = false;
}
}).catch((err)=>{
this.isloading = false;
});
if(blom) return;
this.downloadVisible = false;
},
tip:
这里有一个很关键的地方,就是JSON.parse(fileReader.result).errors.message;
转错误信息的时候,必须放在fileReader.onload
里面,因为readAsText()
必须要挂载 实例下的 onload 或 onloadend 的方法处理转化后的结果,要不然获取不到readAsText的转化结果,详细可看下图:
图片来源链接
这里有一篇讲解的十分详细的参考文章,里面有两种方式
......
}).then(response => {
const resData = response.data
const fileReader = new FileReader()
fileReader.onloadend = () => {
// 此处两种判断返回信息的方法可选其一
// 方法一:
try {
const jsonData = JSON.parse(fileReader.result) // 说明是普通对象数据,后台转换失败
// 后台信息
console.log(jsonData)
} catch (err) { // 解析成对象失败,说明是正常的文件流
// 下载文件
downloadFile(resData)
}
// 方法二:
if (resData.type === 'application/json') {
const jsonData = JSON.parse(fileReader.result) // 说明是普通对象数据,后台转换失败
// 后台信息
console.log(jsonData)
} else {
// 下载文件
downloadFile()
}
}
fileReader.readAsText(resData)
})
function downloadFile (resData) {
const link = document.createElement('a')
let blob = new Blob([resData], {type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=UTF-8'})
link.style.display = 'none'
link.href = URL.createObjectURL(blob)
link.setAttribute('download', '下载文件.xlsx') // 文件名可自定义
document.body.appendChild(link)
link.click()
document.body.removeChild(link)
}