当前位置:主页 > 查看内容

vue axios 文件流导出功能 表格 zip 都可以

发布时间:2021-09-09 00:00| 位朋友查看

简介:API接口代码 因为数据返回的是一个流文件所以必须加上 responseType: ‘blob’ export const getExport async params { try { const data await axios . post ( /xxxxxx/xxxxx , { ... params } , { responseType : blob } ) ; return data ; } catch ( erro……

API接口代码

因为数据返回的是一个流文件,所以必须加上 responseType: ‘blob’

export const getExport = async params => {
  try {
    const data = await axios.post('/xxxxxx/xxxxx',
    { ...params },
    { responseType: 'blob' });
    return data;
  } catch (error) {
    return Promise.reject(error);
  }
};

数据请求

private async getExportData() {
    try {
      this.exportStatus = true;
      this.exportTitle = '正在导出...';
      const resp = await Service.getExport({
        groupSerial: this.formData.parentSerial,
      });
      if (resp.data.type === 'application/vnd.ms-excel') {
        const blob = new Blob([resp.data], {
          type: resp.headers['Content-Type'],
        });
        if (resp && resp.headers['content-disposition']) {
          const filename = resp.headers['content-disposition'].split('=')[1];
          const link = document.createElement('a');
          link.style.display = 'none';
          link.href = URL.createObjectURL(blob);
          link.setAttribute('download', filename);
          document.body.appendChild(link);
          link.click();
          document.body.removeChild(link);
        }
      } else {
        // 错误时需要把blob 转换成json格式,并获取报错信息
        await fileToJson(resp.data)
          .then(res => {
            this.$message.error((res as any).errorMsg);
          })
          .catch(error => {
            /* tslint:disable */
            console.log('error', '\n', error);
            /* tslint:enable */
          });
      }
    } catch (error) {
      /* tslint:disable */
      console.log('error', '\n', error);
      /* tslint:enable */
    } finally {
      this.exportStatus = false;
      this.exportTitle = '确定';
    }
  }

正确的数据返回

正确的数据返回格式

错误时数据返回

错误
不管是正确还是错误请求的状态都是200 ,对于后端来说这只是一个下载功能。错误时通过axios 的响应拦截器根本不行,因为返回的status是200。但是错误时也必须要处理呀。因为我们请求时responseType: ‘blob’ ,Blob ,Blob ,Blob , 直接获取返回的错误信息是不行的。所以需要转换。代码如下,自己封装成了异步。

// 文件流到处错误是,捕获异常
export const  fileToJson = (file) => {
  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.onload = res => {
      const { result }: any = res.target; // 得到字符串
      const data = JSON.parse(result); // 解析成json对象
      resolve(data);
    }; // 成功回调
    reader.onerror = err => {
      reject(err);
    }; // 失败回调
    reader.readAsText(new Blob([file]), 'utf-8'); // 按照utf-8编码解析
  });
};
;原文链接:https://blog.csdn.net/lzt199931415926/article/details/115907125
本站部分内容转载于网络,版权归原作者所有,转载之目的在于传播更多优秀技术内容,如有侵权请联系QQ/微信:153890879删除,谢谢!
上一篇:C++——HIS排班系统for Neuedu 下一篇:没有了

推荐图文


随机推荐