vue實(shí)現(xiàn)文件下載

文件下載有很多種方式,本文主要介紹7種。

一、a標(biāo)簽下載

<body>
  <button onclick="downloadEvt('http://192.168.66.183:13666/download?name=HAP.pdf')">a標(biāo)簽下載</button>
  <script>
    function downloadEvt(url, fileName = '未知文件') {
      const el = document.createElement('a');
      el.style.display = 'none';
      el.setAttribute('target', '_blank');
     /**
       * download的屬性是HTML5新增的屬性
       * href屬性的地址必須是非跨域的地址,如果引用的是第三方的網(wǎng)站或者說(shuō)是前后端分離的項(xiàng)目(調(diào)用后臺(tái)的接口),這時(shí)download就會(huì)不起作用。
       * 此時(shí),如果是下載瀏覽器無(wú)法解析的文件,例如.exe,.xlsx..那么瀏覽器會(huì)自動(dòng)下載,但是如果使用瀏覽器可以解析的文件,比如.txt,.png,.pdf....瀏覽器就會(huì)采取預(yù)覽模式
       * 所以,對(duì)于.txt,.png,.pdf等的預(yù)覽功能我們就可以直接不設(shè)置download屬性(前提是后端響應(yīng)頭的Content-Type: application/octet-stream,如果為application/pdf瀏覽器則會(huì)判斷文件為 pdf ,自動(dòng)執(zhí)行預(yù)覽的策略)
       */
      fileName && el.setAttribute('download', fileName);
      el.href = url;
      console.log(el);
      document.body.appendChild(el);
      el.click();
      document.body.removeChild(el);
    }
  </script>
</body>

優(yōu)點(diǎn)

  • 可以下載txt、png、pdf等類型文件
  • download的屬性是HTML5新增的屬性
    href屬性的地址必須是非跨域的地址,如果引用的是第三方的網(wǎng)站或者說(shuō)是前后端分離的項(xiàng)目(調(diào)用后臺(tái)的接口),這時(shí)download就會(huì)不起作用。 此時(shí),如果是下載瀏覽器無(wú)法解析的文件,例如.exe,.xlsx..那么瀏覽器會(huì)自動(dòng)下載,但是如果使用瀏覽器可以解析的文件,比如.txt,.png,.pdf....瀏覽器就會(huì)采取預(yù)覽模式;所以,對(duì)于.txt,.png,.pdf等的預(yù)覽功能我們就可以直接不設(shè)置download屬性(前提是后端響應(yīng)頭的Content-Type: application/octet-stream,如果為application/pdf瀏覽器則會(huì)判斷文件為 pdf ,自動(dòng)執(zhí)行預(yù)覽的策略)

缺點(diǎn)

  • a標(biāo)簽只能做get請(qǐng)求,所有url有長(zhǎng)度限制
  • 無(wú)法獲取下載進(jìn)度
  • 無(wú)法在header中攜帶token做鑒權(quán)操作
  • 跨域限制
  • 無(wú)法判斷接口是否返回成功
  • IE兼容問(wèn)題

二、form標(biāo)簽下載

圖2-1
<body>
  <button onclick="inputDownloadEvt('get', 'http://192.168.66.183:13666/download', 'name', 'HAP.pdf')">form標(biāo)簽下載</button>
  <script>
    /**
     * @param {String} method - 請(qǐng)求方法get/post
     * @param {String} url
     * @param {String} paramsKey - 請(qǐng)求參數(shù)名
     * @param {String} paramsValue - 請(qǐng)求參數(shù)值
    */
    function inputDownloadEvt(method, url, paramsKey, paramsValue) {
      const form = document.createElement('form');
      form.style.display = 'none';
      form.setAttribute('target', '_blank');
      form.setAttribute('method', method);
      form.setAttribute('action', url);
      const input = document.createElement('input');
      input.setAttribute('type','hidden');
      // 對(duì)于get請(qǐng)求 最終會(huì)拼成http://192.168.66.183:13666/download?name=HAP.pdf
      input.setAttribute('name', paramsKey);
      input.setAttribute('value', paramsValue);
      form.appendChild(input);
      document.body.appendChild(form);
      form.submit();
      document.body.removeChild(form);
    }
  </script>
</body>

優(yōu)點(diǎn)

  • 兼容性好,不會(huì)出現(xiàn)URL長(zhǎng)度限制問(wèn)題
  • form標(biāo)簽get和post都可以

缺點(diǎn)

  • 無(wú)法獲取下載進(jìn)度
  • 無(wú)法在header中攜帶token做鑒權(quán)操作
  • 無(wú)法直接下載瀏覽器可直接預(yù)覽的文件類型(txt、png、pdf會(huì)直接預(yù)覽)
  • 無(wú)法判斷接口是否返回成功

三、window.open下載

<body>
  <button onclick="downloadEvt('http://192.168.66.183:13666/download?name=HAP.pdf')">window.open下載</button>
  <script>
    function downloadEvt(url) {
      window.open(url, '_self');
    }
  </script>
</body>

優(yōu)點(diǎn)

  • 簡(jiǎn)單方便直接

缺點(diǎn)

  • 會(huì)出現(xiàn)URL長(zhǎng)度限制問(wèn)題
  • 需要注意url編碼問(wèn)題
  • 無(wú)法獲取下載進(jìn)度
  • 無(wú)法在header中攜帶token做鑒權(quán)操作
  • 無(wú)法直接下載瀏覽器可直接預(yù)覽的文件類型(txt、png、pdf會(huì)直接預(yù)覽)
  • 無(wú)法判斷接口是否返回成功

四、iframe下載

<body>
  <button onclick="downloadEvt('http://192.168.66.183:13666/download?name=HAP.pdf')">iframe下載</button>
  <script>
    // 批量下載時(shí),動(dòng)態(tài)創(chuàng)建a標(biāo)簽,會(huì)始終只下載一個(gè)文件,改為動(dòng)態(tài)創(chuàng)建iframe標(biāo)簽
    function downloadEvt(url) {
      const iframe = document.createElement('iframe');
      iframe.style.display = 'none';
      iframe.src = url;
      document.body.appendChild(iframe);
      setTimeout(() => {
        document.body.removeChild(iframe);
      }, 200);
    }
  </script>
</body>

優(yōu)點(diǎn)

  • 可以下載txt、png、pdf等類型文件

缺點(diǎn)

  • 無(wú)法獲取下載進(jìn)度
  • 無(wú)法在header中攜帶token做鑒權(quán)操作
  • 無(wú)法判斷接口是否返回成功
  • 兼容、性能差

五、location.href下載

<body>
  <button onclick="downloadEvt('http://192.168.66.183:13666/download?name=HAP.pdf')">location.href下載</button>
  <script>
    function downloadEvt(url) {
      window.location.href = url;
    }
  </script>
</body>

優(yōu)點(diǎn)

  • 簡(jiǎn)單方便直接
  • 可以下載大文件(G以上)

缺點(diǎn)

  • 會(huì)出現(xiàn)URL長(zhǎng)度限制問(wèn)題
  • 需要注意url編碼問(wèn)題
  • 無(wú)法獲取下載進(jìn)度
  • 無(wú)法在header中攜帶token做鑒權(quán)操作
  • 無(wú)法直接下載瀏覽器可直接預(yù)覽的文件類型(txt、png、pdf會(huì)直接預(yù)覽)
  • 無(wú)法判斷接口是否返回成功

六、ajax下載(Blob - 利用Blob對(duì)象生成Blob URL

如果后端需要做token驗(yàn)證,那么a、form、iframe、window.open、location.href都無(wú)法在header中攜帶token,這時(shí)候可以使用ajax來(lái)實(shí)現(xiàn)。

<body>
  <button onclick="downLoadAjaxEvt('get', 'http://192.168.66.183:13666/download?name=HAP.pdf')">ajax下載</button>
  <script>
    function downloadEvt(url, fileName = '未知文件') {
      const el = document.createElement('a');
      el.style.display = 'none';
      el.setAttribute('target', '_blank');
     /**
       * download的屬性是HTML5新增的屬性
       * href屬性的地址必須是非跨域的地址,如果引用的是第三方的網(wǎng)站或者說(shuō)是前后端分離的項(xiàng)目(調(diào)用后臺(tái)的接口),這時(shí)download就會(huì)不起作用。
       * 此時(shí),如果是下載瀏覽器無(wú)法解析的文件,例如.exe,.xlsx..那么瀏覽器會(huì)自動(dòng)下載,但是如果使用瀏覽器可以解析的文件,比如.txt,.png,.pdf....瀏覽器就會(huì)采取預(yù)覽模式
       * 所以,對(duì)于.txt,.png,.pdf等的預(yù)覽功能我們就可以直接不設(shè)置download屬性(前提是后端響應(yīng)頭的Content-Type: application/octet-stream,如果為application/pdf瀏覽器則會(huì)判斷文件為 pdf ,自動(dòng)執(zhí)行預(yù)覽的策略)
       */
      fileName && el.setAttribute('download', fileName);
      el.href = url;
      console.log(el);
      document.body.appendChild(el);
      el.click();
      document.body.removeChild(el);
    };

    // 根據(jù)header里的contenteType轉(zhuǎn)換請(qǐng)求參數(shù)
    function transformRequestData(contentType, requestData) {
      requestData = requestData || {};
      if (contentType.includes('application/x-www-form-urlencoded')) {
        // formData格式:key1=value1&key2=value2,方式二:qs.stringify(requestData, {arrayFormat: 'brackets'}) -- {arrayFormat: 'brackets'}是對(duì)于數(shù)組參數(shù)的處理
        let str = '';
        for (const key in requestData) {
          if (Object.prototype.hasOwnProperty.call(requestData, key)) {
            str += `${key}=${requestData[key]}&`;
          }
        }
        return encodeURI(str.slice(0, str.length - 1));
      } else if (contentType.includes('multipart/form-data')) {
        const formData = new FormData();
        for (const key in requestData) {
          const files = requestData[key];
          // 判斷是否是文件流
          const isFile = files ? files.constructor === FileList || (files.constructor === Array && files[0].constructor === File) : false;
          if (isFile) {
            for (let i = 0; i < files.length; i++) {
              formData.append(key, files[i]);
            }
          } else {
            formData.append(key, files);
          }
        }
        return formData;
      }
      // json字符串{key: value}
      return Object.keys(requestData).length ? JSON.stringify(requestData) : '';
    }
    /**
     * ajax實(shí)現(xiàn)文件下載、獲取文件下載進(jìn)度
     * @param {String} method - 請(qǐng)求方法get/post
     * @param {String} url
     * @param {Object} [params] - 請(qǐng)求參數(shù),{name: '文件下載'}
     * @param {Object} [config] - 方法配置
     */
     function downLoadAjaxEvt(method = 'get', url, params, config) {
      const _method = method.toUpperCase();
      const _config = Object.assign({
        contentType: _method === 'GET' ? 'application/x-www-form-urlencoded' : 'application/json',  // 請(qǐng)求頭類型
        fileName: '未知文件',                                        // 下載文件名(必填,若為空,下載下來(lái)都是txt格式)
        async: true,                                                // 請(qǐng)求是否異步-true異步、false同步
        token: 'token'                                              // 用戶token
      }, config);

      const queryParams = transformRequestData(_config.contentType, params);
      const _url = `${url}${_method === 'GET' && queryParams ? '?' + queryParams : ''}`;

      const ajax = new XMLHttpRequest();
      ajax.open(_method, _url, _config.async);
      ajax.setRequestHeader('Authorization', _config.token);
      ajax.setRequestHeader('Content-Type', _config.contentType);
      // responseType若不設(shè)置,會(huì)導(dǎo)致下載的文件可能打不開(kāi)
      ajax.responseType = 'blob';
      // 獲取文件下載進(jìn)度
      ajax.addEventListener('progress', (progress) => {
        const percentage = ((progress.loaded / progress.total) * 100).toFixed(2);
        const msg = `下載進(jìn)度 ${percentage}%...`;
        console.log(msg);
      });
      ajax.onload = function () {
        if (this.status === 200 || this.status === 304) {
          // 通過(guò)FileReader去判斷接口返回是json還是文件流
          const fileReader = new FileReader();
          fileReader.onloadend = (e) => {
            if (this.getResponseHeader('content-type').includes('application/json')) {
              const result = JSON.parse(fileReader.result || '{message: 服務(wù)器出現(xiàn)問(wèn)題,請(qǐng)聯(lián)系管理員}');
              alert(result.message);
            } else {
              // 兩種解碼方式,區(qū)別自行百度: decodeURIComponent/decodeURI(主要獲取后綴名,否則低版本瀏覽器會(huì)一律識(shí)別為txt,導(dǎo)致下載下來(lái)的都是txt)
              const _fileName = decodeURIComponent((this.getResponseHeader('content-disposition') || '; filename="未知文件"').split(';')[1].trim().slice(9));
              /**
              * Blob.type一個(gè)字符串,表明該 Blob 對(duì)象所包含數(shù)據(jù)的 MIME 類型。如果類型未知,則該值為空字符串。
              * 對(duì)于pdf:type為application/pdf  同時(shí) a標(biāo)簽 不設(shè)置download屬性, 可以直接預(yù)覽
              */
              const blob = new Blob([this.response]);
              const href = URL.createObjectURL(blob);
              downloadEvt(href, _fileName);
              // 釋放一個(gè)之前已經(jīng)存在的、通過(guò)調(diào)用 URL.createObjectURL() 創(chuàng)建的 URL 對(duì)象
              URL.revokeObjectURL(href);
            }
          };
          // 調(diào)用readAsText讀取文件,少了readAsText將不會(huì)觸發(fā)onloadend事件
          fileReader.readAsText(this.response);
        } else {
          alert('服務(wù)器出現(xiàn)問(wèn)題,請(qǐng)聯(lián)系管理員');
        }
      };
      // send(string): string:僅用于 POST 請(qǐng)求
      ajax.send(queryParams);
    }
  </script>
</body>
  • responseType
    responseType若不設(shè)置,會(huì)導(dǎo)致下載的文件可能打不開(kāi)ajax.responseType = 'blob';
  • new FileReader()
    1.文件下載的接口存在返回失敗的情況(例如:服務(wù)器連接不上、接口報(bào)錯(cuò)等),對(duì)于下載失敗的情況我們需要在頁(yè)面上彈出失敗提示,而不是將失敗信息寫進(jìn)文件里等用戶打開(kāi),這時(shí)候可以使用FileReader去根據(jù)響應(yīng)頭里的content-type判斷接口是否返回成功;
    2.如果content-type返回application/json表示文件流返回失敗,此時(shí)直接在頁(yè)面上彈出失敗信息(圖6-1);如果是其他格式就認(rèn)為文件流已經(jīng)返回。
    圖6-1
  • this.getResponseHeader('content-disposition')
    后端返回的文件名稱,主要獲取后綴名,否則某些瀏覽器會(huì)一律識(shí)別為txt,導(dǎo)致下載下來(lái)的都是txt
    圖6-2
  • new Blob([this.response], {type: '文件類型'}) Application Type 對(duì)照表
    1.Blob.type一個(gè)字符串,表明該 Blob 對(duì)象所包含數(shù)據(jù)的 MIME 類型。如果類型未知,則該值為空字符串;
    2.對(duì)于pdf:type為application/pdf 同時(shí) a標(biāo)簽 不設(shè)置download屬性(圖6-3), 可以直接預(yù)覽(圖6-4)
    圖6-3

    圖6-4
  • axios中其實(shí)已經(jīng)提供了獲取文件上傳和下載進(jìn)度的事件,這里我使用的是原生ajax(axios雷同,只需要修改請(qǐng)求方法)。


    圖6-5

優(yōu)點(diǎn)

  • 可以下載txt、png、pdf等類型文件
  • 可以在header中攜帶token做鑒權(quán)操作
  • 可以獲取文件下載進(jìn)度
  • 可以判斷接口是否返回成功

缺點(diǎn)

  • 兼容性問(wèn)題,IE10以下不可用,注意Safari瀏覽器,官網(wǎng)給出
    Safari has a serious issue with blobs that are of the type application/octet-stream
  • 將后端返回的文件流全部獲取后才會(huì)下載

七、ajax下載(Data URL - base64編碼后的url

<body>
  <button onclick="downLoadAjaxEvt('get', 'http://192.168.66.183:13666/download?name=HAP.pdf')">ajax下載(base64)</button>
  <script>
    function downloadEvt(url, fileName = '未知文件') {
      const el = document.createElement('a');
      el.style.display = 'none';
      el.setAttribute('target', '_blank');
      /**
       * download的屬性是HTML5新增的屬性
       * href屬性的地址必須是非跨域的地址,如果引用的是第三方的網(wǎng)站或者說(shuō)是前后端分離的項(xiàng)目(調(diào)用后臺(tái)的接口),這時(shí)download就會(huì)不起作用。
       * 此時(shí),如果是下載瀏覽器無(wú)法解析的文件,例如.exe,.xlsx..那么瀏覽器會(huì)自動(dòng)下載,但是如果使用瀏覽器可以解析的文件,比如.txt,.png,.pdf....瀏覽器就會(huì)采取預(yù)覽模式
       * 所以,對(duì)于.txt,.png,.pdf等的預(yù)覽功能我們就可以直接不設(shè)置download屬性(前提是后端響應(yīng)頭的Content-Type: application/octet-stream,如果為application/pdf瀏覽器則會(huì)判斷文件為 pdf ,自動(dòng)執(zhí)行預(yù)覽的策略)
       */
      fileName && el.setAttribute('download', fileName);
      el.href = url;
      console.log(el);
      document.body.appendChild(el);
      el.click();
      document.body.removeChild(el);
    };

    // 根據(jù)header里的contenteType轉(zhuǎn)換請(qǐng)求參數(shù)
    function transformRequestData(contentType, requestData) {
      requestData = requestData || {};
      if (contentType.includes('application/x-www-form-urlencoded')) {
        // formData格式:key1=value1&key2=value2,方式二:qs.stringify(requestData, {arrayFormat: 'brackets'}) -- {arrayFormat: 'brackets'}是對(duì)于數(shù)組參數(shù)的處理
        let str = '';
        for (const key in requestData) {
          if (Object.prototype.hasOwnProperty.call(requestData, key)) {
            str += `${key}=${requestData[key]}&`;
          }
        }
        return encodeURI(str.slice(0, str.length - 1));
      } else if (contentType.includes('multipart/form-data')) {
        const formData = new FormData();
        for (const key in requestData) {
          const files = requestData[key];
          // 判斷是否是文件流
          const isFile = files ? files.constructor === FileList || (files.constructor === Array && files[0].constructor === File) : false;
          if (isFile) {
            for (let i = 0; i < files.length; i++) {
              formData.append(key, files[i]);
            }
          } else {
            formData.append(key, files);
          }
        }
        return formData;
      }
      // json字符串{key: value}
      return Object.keys(requestData).length ? JSON.stringify(requestData) : '';
    }
    /**
     * ajax實(shí)現(xiàn)文件下載、獲取文件下載進(jìn)度
     * @param {String} method - 請(qǐng)求方法get/post
     * @param {String} url
     * @param {Object} [params] - 請(qǐng)求參數(shù),{name: '文件下載'}
     * @param {Object} [config] - 方法配置
     */
     function downLoadAjaxEvt(method = 'get', url, params, config) {
      const _method = method.toUpperCase();
      const _config = Object.assign({
        contentType: _method === 'GET' ? 'application/x-www-form-urlencoded' : 'application/json',  // 請(qǐng)求頭類型
        fileName: '未知文件',                                       // 下載文件名(必填,若為空,下載下來(lái)都是txt格式)
        async: true,                                               // 請(qǐng)求是否異步-true異步、false同步
        token: 'token'                                             // 用戶token
      }, config);

      const queryParams = transformRequestData(_config.contentType, params);
      const _url = `${url}${_method === 'GET' && queryParams ? '?' + queryParams : ''}`;

      const ajax = new XMLHttpRequest();
      ajax.open(_method, _url, _config.async);
      ajax.setRequestHeader('Authorization', _config.token);
      ajax.setRequestHeader('Content-Type', _config.contentType);
      // responseType若不設(shè)置,會(huì)導(dǎo)致下載的文件可能打不開(kāi)
      ajax.responseType = 'blob';
      // 獲取文件下載進(jìn)度
      ajax.addEventListener('progress', (progress) => {
        const percentage = ((progress.loaded / progress.total) * 100).toFixed(2);
        const msg = `下載進(jìn)度 ${percentage}%...`;
        console.log(msg);
      });
      ajax.onload = function () {
        if (this.status === 200 || this.status === 304) {
          // 通過(guò)FileReader去判斷接口返回是json還是文件流
          const fileReader = new FileReader();
          fileReader.readAsDataURL(this.response);
          fileReader.onload = () => {
            if (this.getResponseHeader('content-type').includes('application/json')) {
              alert('服務(wù)器出現(xiàn)問(wèn)題,請(qǐng)聯(lián)系管理員');
            } else {
              // 兩種解碼方式,區(qū)別自行百度: decodeURIComponent/decodeURI(主要獲取后綴名,否則某些瀏覽器會(huì)一律識(shí)別為txt,導(dǎo)致下載下來(lái)的都是txt)
              const _fileName = decodeURIComponent((this.getResponseHeader('content-disposition') || '; filename="未知文件"').split(';')[1].trim().slice(9));
              // 也可以用FileSaver(需提前引入https://github.com/eligrey/FileSaver.js): saveAs(fileReader.result, _fileName);
              downloadEvt(fileReader.result, _fileName);
            }
          }
        } else {
          alert('服務(wù)器出現(xiàn)問(wèn)題,請(qǐng)聯(lián)系管理員');
        }
      };
      // send(string): string:僅用于 POST 請(qǐng)求
      ajax.send(queryParams);
    }
  </script>
</body>
  • fileSaver
    網(wǎng)上介紹很多,可以自己百度下

優(yōu)點(diǎn)

  • 可以下載txt、png、pdf等類型文件
  • 可以在header中攜帶token做鑒權(quán)操作
  • 可以獲取文件下載進(jìn)度
  • 可以判斷接口是否返回成功

缺點(diǎn)

  • 兼容性問(wèn)題,IE10以下不可用
  • 將后端返回的文件流全部獲取后才會(huì)下載

八、大文件下載注意點(diǎn)

  • fileSaver
    批量下載時(shí),總量不超過(guò)2G可以用下這個(gè),但是每個(gè)瀏覽器允許下載的最大文件不一樣~
    圖8-1
  • ajax下載
    如果后端需要對(duì)下載接口做token鑒權(quán),此時(shí)需要使用ajax獲取文件流(第六、七點(diǎn)),可以了解下ajax文件下載原理。
    簡(jiǎn)單來(lái)說(shuō),文件下載依賴瀏覽器特性。前端獲取到服務(wù)器端生成的字節(jié)流,此時(shí)數(shù)據(jù)是存在于js的內(nèi)存中的,是不可以直接保存在本地的,利用Blob對(duì)象和window.URL.createObjectURL對(duì)象生成一個(gè)虛擬的URL地址,然后在利用瀏覽器的特性進(jìn)行下載。
    因此對(duì)于ajax下載大文件時(shí),會(huì)出現(xiàn)瀏覽器崩潰情況,此時(shí)可以考慮使用鏈接直接下載或使用分片下載
    圖8-2
  • 鏈接下載
    鏈接下載需要后端一邊去下載要打包的文件,一邊把打包好的東西寫入這個(gè)鏈接。存在的問(wèn)題是,如果文件很大,那么這個(gè)鏈接需要一直保持,相當(dāng)于這個(gè)接口一直開(kāi)著沒(méi)有結(jié)束;而且一旦中間出了什么問(wèn)題,已經(jīng)下載的東西也全部廢了,因此推薦使用分片下載。

相關(guān)文章

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容