post方法下載文件


下載文件,一般后台返回的是文件流。前台如果用的fetch的話,respose里面是空的,什么也看不到。用的axios的話,是一堆字符串形式的東西。

封裝請求方法的時候,用 response.headers.get('Content-Type').includes('application/json') 來判斷返回結果是不是文件流, 為true的話就不是文件流.

文件的名稱要從header里面去取(跨域的時候是取不到的,需要掛nginx)

// 這個是封裝請求時獲取文件名稱的方法

.then((respose) => {

  let filename = '';
         const disposition = response.headers.get('Content-Disposition');
          if (disposition && disposition.indexOf('attachment') !== -1) {
            const filenameRegex = /filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/;
            const matches = filenameRegex.exec(disposition);
            if (matches != null && matches[1]) filename = decodeURIComponent(matches[1].replace(/['"]/g, ''));
          }
        const res = {
          data: response.blob(),
          filename,
        };
        return res;

})

// 這個是接口成功之后的操作,需要注意的是,如果接口失敗,返回的一定是json字符串,這里要做判斷

callback: ((res) => { 

  Promise.resolve(res.data)
          .then((blob) => {
             this.postDownload(blob, res.filename);
          });

})

 

postDownload = (blob, filename) => {
      if (typeof window.navigator.msSaveBlob !== 'undefined') {
        // IE
        window.navigator.msSaveBlob(blob, filename);
      } else {
        const URL = window.URL || window.webkitURL;
        const downloadUrl = URL.createObjectURL(blob);
        if (filename) {
          // use HTML5 a[download] attribute to specify filename
          const a = document.createElement('a');
          // safari doesn't support this yet
          if (typeof a.download === 'undefined') {
            window.location = downloadUrl;
          } else {
            a.href = downloadUrl;
            a.target = '_blank';
            a.download = filename;
            document.body.appendChild(a);
            a.click();
          }
        } else {
          window.location = downloadUrl;
        }
        setTimeout(() => { URL.revokeObjectURL(downloadUrl); }, 100); // cleanup
      }
    },


免責聲明!

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



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