前端下載文件的幾種方式


1.請求獲取后端生成的文件url地址

    downloadFile(url) {
      //下載文件
      var a = document.createElement("a");
      a.setAttribute("href", url);
      a.setAttribute("target", "_blank");
      let clickEvent = document.createEvent("MouseEvents");
      clickEvent.initEvent("click", true, true);
      a.dispatchEvent(clickEvent);
    },

2.請求后端返回數據本身的流文件

(1) 呈現在用戶面前的文件結構叫做文件的邏輯結構,邏輯結構分為兩種:一種是記錄式文件,另一種為流式文件。流文件 就是沒有結構的文件。

(2) Blob 對象表示一個不可變、原始數據的類文件對象。Blob 表示的不一定是JavaScript原生格式的數據。

      // 使用Blob
      let blob = new Blob([res.data], { type: `text/plain;charset=utf-8` });
      // 獲取heads中的filename文件名
      let downloadElement = document.createElement("a");
      // 創建下載的鏈接
      let href = window.URL.createObjectURL(blob);
      downloadElement.href = href;
      // 下載后文件名
      downloadElement.download = "文件名";
      document.body.appendChild(downloadElement);
      // 點擊下載
      downloadElement.click();
      // 下載完成移除元素
      document.body.removeChild(downloadElement);
      // 釋放掉blob對象

3.后端直接返回某種格式的數據本身

    download(filename, text) {
      var pom = document.createElement("a");
      pom.setAttribute(
        "href",
        "data:text/plain;charset=utf-8," + encodeURIComponent(text)
      );
      pom.setAttribute("download", filename);
      if (document.createEvent) {
        var event = document.createEvent("MouseEvents");
        event.initEvent("click", true, true);
        pom.dispatchEvent(event);
      } else {
        pom.click();
      }
    },

參考文檔:

https://www.cnblogs.com/woai3c/p/11262491.html

https://www.cnblogs.com/xiaohi/p/6550133.html

https://blog.csdn.net/qq_33592641/article/details/104991704

 


免責聲明!

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



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