前端vue导出后端返回的word excel zip流文件下载

在日常开发中,我们可能会遇到导出excel word的情况,而后端此时给我们返回的是一个文件流,需要前端将文件流转为url地址进行下载。 可以将这个方法封装成一个工具类,方便其他地方调用,我这里放到了utils.js里面

js:

export function exportFile(data,type, fileName) {
    let blob = new Blob([data], {
      //type类型后端返回来的数据中会有,根据自己实际进行修改
      // 表格下载为 application/xlsx,压缩包为 application/zip等,
      type: type
    });
    let filename = fileName;
    if (typeof window.navigator.msSaveBlob !== "undefined") {
      window.navigator.msSaveBlob(blob, filename);
    } else {
      var blobURL = window.URL.createObjectURL(blob);
      // 创建隐藏<a>标签进行下载
      var tempLink = document.createElement("a");
      tempLink.style.display = "none";
      tempLink.href = blobURL;
      tempLink.setAttribute("download", filename);
      if (typeof tempLink.download === "undefined") {
        tempLink.setAttribute("target", "_blank");
      }
      document.body.appendChild(tempLink);
      tempLink.click();
      document.body.removeChild(tempLink);//移除dom元素
      window.URL.revokeObjectURL(blobURL);//释放bolb内存
    }
  }
在vue中引用该方法
        //导出文件方法
        exportFile() {
            let obj = {
                dataid: this.companyInfo.dataId,
                id: this.companyInfo.id,
                template: this.radio,
                year: this.companyInfo.year
            }
            exportWordForQuality(obj)
                .then(res => {
                    console.log('质量审核-填报说明导出:', res.data);
                    const { data } = res
                    let fileName = `${this.companyObj.companyName}执行报告审核意见`
                    exportFile(data, 'application/vnd.openxmlformats-officedocument.wordprocessingml.document', fileName)
                })
                .catch(err => {
                    console.log(err);
                })

        },
注意:
(1)本方法中并没有设计压缩,如倒出的文件大,强烈建议使用jsZip
先安装在使用:import JSZip from 'jszip'
(2)exportWordForQuality ()接口中的响应格式要设置为bolb
//下载质量审核文件
export function exportWordForQuality(data) {
    return req.post('/qualityAudit/report/exportWordForQuality', data, {
        'responseType': 'blob'
    })
}
(3)网页响应头content-type:
word文件:
.doc格式的content-type设置为:application/vnd.msword;charset=utf-8 
.docx格式的content-type设置为:application/vnd.openxmlformats-officedocument.wordprocessingml.document
excel文件:
.xls格式的content-type设置为:application/vnd.ms-excel
.xlsx格式的content-type设置为:application/vnd.openxmlformats-officedocument.spreadsheetml.sheet
 zip文件:
. zip格式的content-type设置为:application/zip
 
关于content-type设置格式参考:https://www.ibm.com/docs/en/wkc/cloud?topic=catalog-previews
 
posted @ 2022-05-05 10:07  赵辉Coder  阅读(2199)  评论(0编辑  收藏  举报