前端JS下載文件總結


Data URLs

        Data URLs: 即前綴為data: 協議的URL,其允許內容創建者向文檔中嵌入小文件。

  例如:可以直接在HTML中的img元素直接使用Data URLs ;

data:[<mediatype>][;base64],<data>
  • mediatype: 是個 MIME 類型的字符串,例如 "image/jpeg" 表示 JPEG 圖像文件,'text/plain' 則表示txt文件,"excel/plain" 則表示excel文件;如果被省略,則默認值為 text/plain;charset=US-ASCII。
  • base64:即是base64編碼,如果data是文本格式,可以直接嵌入文本。如下:
data:,Hello%2C%20World!  // text/plain 類型數據
data:text/plain;base64,SGVsbG8sIFdvcmxkIQ%3D%3D  // base64 編碼版本

  如果是二進制數據,可以進行base64編碼之后再進行嵌入。在JavaScript中,有兩個函數btoa()atob()分別用於解碼和編碼base64字符串。

Blob

       Blob 對象表示一個不可變、原始數據的類文件對象,其中Blob.size代表對象中所包含數據的大小(字節),Blob.type 表明該Blob對象所包含數據的 MIME 類型。

  其方法主要是blob.arrayBuffer()返回一個promise且包含blob所有內容的二進制格式的ArrayBuffer。

// 可以直接創建一個簡單的文本Blob對象
new Blob(["hello world"]) 
 // 一個包含DOMString的數組,然后創建一個HTML類型的Blob對象
new Blob(["hello world".bold()], {type : 'text/html'});

  了解了上面的概念之后,步入正題

  1. 最簡單的方式,比如下載圖片,可以讓后端以附件的形式下載,加以下面代碼downloadSimple()方法,就可以下載圖片文件了。

  downloadSimple(url: string, fileName: string) {
     const anchor = document.createElement('a');
      const fileName = fileName || 'download';
      if ('download' in anchor) { //html5 A[download]
        anchor.href = url;
        anchor.setAttribute("download", fileName);
        anchor.className = "download-js-link";
        anchor.innerHTML = "downloading...";
        anchor.style.display = "none";
        document.body.appendChild(anchor);
        setTimeout(function () {
          anchor.click();
          document.body.removeChild(anchor);
        }, 66);
        return true;
      }
   }

  2.GET請求下載,且responseType為blob。代碼如下:(Get方法長度限制最大不要超過2048,即2048+35。這里要解釋一下,其實get方法並沒有限制URL最大長度限制,是瀏覽器的限制要求,而這個2083就是IE瀏覽器限制的最大長度,也是各個瀏覽器當中最小)。

 if (url && url.length < 2048) {
      fileName = url.split("/").pop().split("?")[0];
      anchor.href = url;
      if (anchor.href.indexOf(url) !== -1) {
        var ajax = new XMLHttpRequest();
        ajax.open("GET", url, true);
        ajax.responseType = 'blob';
        ajax.onload = function (e:any) {
          _this.downloadSimple(e.target.response, fileName); // 調用上面的a標簽式下載方法
        };
        setTimeout(function () { ajax.send(); }, 0);
        return ajax;
      }
   }

  3.POST方式下載,且后端返回base64編碼格式的數據流,類似於這種(ZtjuPPe2d+GefPrD1RpnS6MGdJkebn4/+oMSAAOw==),然后可以拼接成Data URLs格式,用以上的代碼段downloadSimple()就可以直接下載文件,如果是下載excel文件,則Data URLs的參數mediatype為"excel/plain" 。

  但是如果是IE瀏覽器用這種代碼不行,可以用navigator.msSaveBlob()方法下載一個Blob 對象。首先需要把Data URLs轉換成可供瀏覽器下載的Blob 對象。方法如下:

  

    function dataUrlToBlob(strUrl: string) {
      var parts = strUrl.split(/[:;,]/),
        type = parts[1],
        decoder = parts[2] == "base64" ? atob : decodeURIComponent,
        binData = decoder(parts.pop()),
        mx = binData.length,
        i = 0,
        uiArr = new Uint8Array(mx);

      for (i; i < mx; ++i) uiArr[i] = binData.charCodeAt(i);

      return new myBlob([uiArr], { type: type });
    }
  navigator.msSaveBlob(dataUrlToBlob(url));

 


免責聲明!

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



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