前端接收后端文件流導出excel文檔遇到的問題


先上代碼:

Vue.prototype.download = function(oUrl, filename) {
  this.axios
    .get(oUrl, { responseType: 'arraybuffer' })
    .then((res) => {
      console.log(res);
      // type 為需要導出的文件類型,此處為xls表格類型
      const blob = new Blob([res.data], { type: 'application/vnd.ms-excel' });
      // 兼容不同瀏覽器的URL對象
      const url = window.URL || window.webkitURL || window.moxURL;
      // 創建下載鏈接
      const downloadHref = url.createObjectURL(blob);
      // 創建a標簽並為其添加屬性
      let downloadLink = document.createElement('a');
      downloadLink.target = '_blank';
      downloadLink.href = downloadHref;
      filename = filename ? filename : new Date().getTime();
      downloadLink.download = filename + '.xls';
      // 觸發點擊事件執行下載
      downloadLink.click();
    })
    .catch((err) => {
      console.error(err);
    });
  // window.open(location.origin + axios.defaults.baseURL + oUrl); //直接跳轉文件地址下載,有些頁面無法正常下載,暫未解決,待排查。
};

請求一定要設置

responseType: 'arraybuffer'

createObjectURL(blob)中的地址一定要是Blob對象:

const blob = new Blob([res.data], { type: 'application/vnd.ms-excel' });


免責聲明!

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



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