Vue导出后台返回的Excel文件及JSON文件异常处理。

1,460 阅读2分钟

文件导出

utils.js 封装的方法

/**
 * 下载文件excel的封装
 * @param {string} file_name 需要传入的文件名
 * @param {blob} content 后台返回的blob流
 */
const downFile = (content, file_name = "下载文件") => {
  const csvData = new Blob([content], {
    type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" //文件类型
  });
  if (window.navigator.msSaveOrOpenBlob) {
    // for IE
    // window.navigator.msSaveOrOpenBlob(csvData, file_name);
    window.navigator.msSaveBlob(csvData, `${file_name}.xlsx`);
  } else {
    // for Non-IE (chrome, firefox etc.)
    let a = document.createElement("a");
    document.body.appendChild(a);
    a.style = "display: none";
    const url = window.URL.createObjectURL(csvData);
    a.href = url;
    a.download = file_name;
    a.click();
    a.remove();
    window.URL.revokeObjectURL(url);
  }
};

export default {
    downFile
}

调用封装好的方法

   async handleExportDatail () {
      await this.$request.downloadMyAftersalesList(this.queryData).then(res => {
        if (res.type == 'application/json') {
          // 文件导出失败 后台返回JSON错误信息处理
          utils.fileExportResponseError(res);
        } else {
          // 文件导出成功
          utils.downFile(res);
        }
      })
    },

注意,接口请求响应类型

{
    name: "downloadMyAftersalesList",
    path: "************",
    requestMethod: "post",
    // 注意一定要加上响应类型
    responseType: "blob"
  },

文件导出失败,处理后台返回JSON错误信息

后端:如果后端说数据太多了,不能一次全导出,我给你返回个JSON错误信息吧。

前端:好的,这还不简单。

image.png 前端:美滋滋

当再次点击导出文件的时候,还是可以导出,接口返回的数据也没问题啊,自己的判断逻辑也没问题呀,哪里出了问题呢?...真相只有一个!于是console.log(res,"导出")打印了一下返回的参数。。。傻眼了

bc759c25c80f277cc3874969b32ceb8.jpg

返回的时候并不是json,json原来在导出的Excel文件里。

4c889d4d64a3480b0a5fbfc2ecd3b77.jpg 这时才醒悟过来,原来请求接口的时候做了响应类型处理。

解决方法

utils.js封装的方法

import { Message } from 'element-ui'

/**
 * 文件导出 后台返回JSON错误信息处理
 * @param 接口返回的数据
 */
export function fileExportResponseError (data) {
  const fileReader = new FileReader();
  fileReader.onload = function () {
    try {
      // 说明是普通对象数据,后台转换失败
      const jsonData = JSON.parse(fileReader.result);
      Message.error(jsonData.message)
    } catch (err) {
      // 解析对象失败,说明是正常的文件流
      console.log(err)
    }
  };
  fileReader.readAsText(data)
}


export default {
    downFile,
    fileExportResponseError
}

调用封装好的方法

   async handleExportDatail () {
      await this.$request.downloadMyAftersalesList(this.queryData).then(res => {
        if (res.type == 'application/json') {
          // 文件导出失败 后台返回JSON错误信息处理
          utils.fileExportResponseError(res);
        } else {
          // 文件导出成功
          utils.downFile(res);
        }
      })
    },