首页 > Web开发 > 详细

设置了responseType:Blob,通过 new FileReader() 解析blob为json,进行处理

时间:2021-03-11 17:24:52      阅读:87      评论:0      收藏:0      [点我收藏+]

axios 设置 responseType:Blob,后台返回的数据会被强制转为blob类型,这时后台返回的数据会有两种情况要处理:

1. 数据异常,后台返回 blob 类型异常信息:

  使用 new FileReader(),将 blob 转为 json,然后进行处理

 

2. 数据正常,后台返回 blob 文件流:

  通过方法,直接下载

 

??????,直接上代码

 1         let that = this
 2         axios.get({
 3           url: ‘xxxxxx‘,
 4           method: ‘get‘,
 5           data:{},
 6           responseType: ‘blob‘, // 后台返回的数据会被强制转为blob类型
 7         }).then(res => {
 8           let reader = new FileReader();
 9           reader.readAsText(res)
10           reader.onload = function (result) {
11             try {
12               let resData = JSON.parse(result.target.result);  // 解析对象成功,说明是json数据
13               if (resData.code) {
14                 that.$message({
15                   type: ‘error‘,
16                   message: resData.desc
17                 })
18               }
19             } catch (err) {   // 解析成对象失败,说明是正常的文件流
20               let blob = new Blob([res], {type: "application/vnd.ms-excel"});
21               var link = document.createElement(‘a‘);
22               link.href = window.URL.createObjectURL(blob);
23               link.download = `文件名.xls`;
24               link.click()
25             }
26           };
27         })

 

设置了responseType:Blob,通过 new FileReader() 解析blob为json,进行处理

原文:https://www.cnblogs.com/liql/p/14516089.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!