【问题标题】:Vue.js Axios responseType blob or json objectVue.js Axios responseType blob 或 json 对象
【发布时间】:2021-04-12 11:22:35
【问题描述】:

我有一个下载 .xls 文件的 Axios 请求。问题是作为来自后端的响应返回的对象并不总是必须是真实文件。如果我返回 json 对象而不是文件数据。那我怎么读这个json呢?

函数如下:

downloadReport() {
  let postConfig = {
    headers: {
      'X-Requested-With': 'XMLHttpRequest'
    },
    responseType: 'blob',
  } as AxiosRequestConfig

  axios
  .post(this.urls.exportDiscountReport, this.discount.id, postConfig)
  .then((response) => {
    let blob = new Blob([response.data], { type: 'application/vnd.ms-excel' });
    let url = window['URL'].createObjectURL(blob);
    let a = document.createElement('a');
    a.href = url;
    a.download = this.discount.id + ' discount draft.xlsx';
    a.click();
    window['URL'].revokeObjectURL(url);
  })
  .catch(error => {
  })
}

我想阅读响应,如果它包含一些数据 - 不要创建 blob 并启动下载,而是只显示一些消息或其他内容。如果我删除 responseType: 'blob' 然后 .xls 文件下载为不可读且无效的文件。

所以问题是每个返回的响应都变成了 blob 类型,我没有在其中看到我返回的数据。有什么想法吗?

【问题讨论】:

    标签: vue.js axios blob


    【解决方案1】:

    您是否尝试过检查responseBlob.type 属性?它给出了返回数据的 MIME 类型。

    所以例如你可以有这样的东西:

    const jsonMimeType = 'application/json';
    const dataType = responseBlob.type;
    
    // The instanceof Blob check here is redundant, however it's worth making sure
    const isBlob = responseBlob instanceof Blob && dataType !== jsonMimeType;
    
    if (isBlob) {
    
      // do your blob download handling
    
    } else {
      responseBlob.text().then(text => {
        const res = JSON.parse(text);
        // do your JSON handling
      });
    }
    

    我发现这更简单并且对我有用,但这取决于您的后端设置。 BLOB 响应仍然是文本响应,但处理方式略有不同。

    【讨论】:

      【解决方案2】:

      我通过读取 blob 响应并检查它是否具有 JSON 参数状态来解决此问题。但这对我来说似乎是过度工程。有没有更好的解决方案?

      let postConfig = {
        headers: {
          'X-Requested-With': 'XMLHttpRequest'
        },
        responseType: 'blob',
      } as AxiosRequestConfig
      
      axios
        .post(this.urls.exportDiscountReport, this.discount.id, postConfig)
        .then((responseBlob) => {
          const self = this;
          let reader = new FileReader();
      
          reader.onload = function() {
            let response = { status: true, message: '' };
      
            try {
              response = JSON.parse(<string>reader.result);
            } catch (e) {}
      
            if (response.status) {
              let blob = new Blob([responseBlob.data], { type: 'application/vnd.ms-excel' });
              let url = window['URL'].createObjectURL(blob);
              let a = document.createElement('a');
              a.href = url;
              a.download = self.discount.id + ' discount draft.xlsx';
              a.click();
              window['URL'].revokeObjectURL(url);
            } else {
              alert(response.message)
            }
          }
          reader.readAsText(responseBlob.data);
        })
        .catch(error => {
        })
      

      我在这里也找到了相同的解决方案:https://github.com/axios/axios/issues/815#issuecomment-340972365

      看起来还是太老套了。

      【讨论】:

        猜你喜欢
        • 2021-09-17
        • 2020-06-12
        • 1970-01-01
        • 2021-11-03
        • 2019-04-29
        • 2017-11-06
        • 2020-07-06
        • 1970-01-01
        • 2020-07-19
        相关资源
        最近更新 更多