前端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
 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM