前端下载文件的几种方式

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

 

posted @ 2020-12-23 13:42  阿玛度の博客  阅读(7444)  评论(0编辑  收藏  举报