• 前端下载文件的几种方式


    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

  • 相关阅读:
    MATLAB新手教程
    关于Core Location-ios定位
    《TCP/IP具体解释卷2:实现》笔记--IP的分片和重装
    利用JasperReport+iReport进行Web报表开发
    Surface、SurfaceView、SurfaceHolder及SurfaceHolder.Callback之间的关系
    Openfire开发配置,Openfire源码配置,OpenFire二次开发配置
    在Activity中为什么要用managedQuery()
    24点经典算法
    linux概念之时间与时区
    java实现第五届蓝桥杯大衍数列
  • 原文地址:https://www.cnblogs.com/amadoGrowers/p/14178183.html
Copyright © 2020-2023  润新知