blob对象转json

5,194 阅读1分钟

场景:文件下载请求时将响应头设置为responseType: 'blob',后端接口成功会返回文件流,错误时返回json,需将blob对象转为json

在响应拦截器中添加可将blob对象转为json

    const res = response.data;
    if (res.type === 'text/html') {
      var enc = new TextDecoder('utf-8');
      res.arrayBuffer().then(buffer => {
        let data = JSON.parse(enc.decode(new Uint8Array(buffer))) || {};
      })
    }

参考:

juejin.cn/post/684490…