axios请求responseType为blob时,错误数据处理

有的时候,我们在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)
}

  • 3
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

echo忘川

谢谢老板们

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值