最近有一个下载文件的需求,后端有数据时返回文件流,没有数据时返回json,前端抛出错误提示
下载接口请求设置为 responseType: ‘blob’,后端返回的json也被转成blob
解决办法:
this.http
.post(
this.commonApilistService.apiList.apis.openapi.export,
params,
undefined,
{
headers: {
contentType: "text/javascript;charset=UTF-8",
},
responseType: "blob",
observe: "response",
}
)
.subscribe((res) => {
const tempBlob = new Blob([res.body], { type: "application/json" });
// 通过 FileReader 读取这个 blob
const reader = new FileReader();
reader.onload = (e) => {
const data = e.target.result;
// 此处对fileReader读出的结果进行JSON解析
// 可能会出现错误,需要进行捕获
try {
// 正常json数据格式
const json = JSON.parse(String(data));
// ...json逻辑处理
} catch (err) {
const a = document.createElement("a");
a.href = URL.createObjectURL(res["body"]);
a.download = res["headers"]
.get("content-disposition")
.split("=")[1];
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
}
};
// 将blob对象以文本的方式读出,读出完成后将会执行 onload 方法
reader.readAsText(tempBlob);
});
欢迎在评论区交流。
如果文章对你有所帮助,❤️关注+点赞❤️鼓励一下!博主会持续更新。。。。
我的博客原文:js处理下载文件接口有时返回文件流有时返回json的情况