zoukankan      html  css  js  c++  java
  • 前端之文件下载的四种方法

    1,最简单的方法是

    window.open("url", "_blank");

    大概原理为:window.open() 作用为打开一个网页,当浏览器检测到url不是一个网页时,他会帮助你进行下载或者打开该文件,不支持对request header的编辑

    于此类似的还有

    window.location.href = url;

    均不建议使用

    2,建议采用blob与Ajax相结合的方法,具体方法参见

    http://www.it1352.com/885919.html 之解决方案

    此时后端会将整个文件通过文件流的方式传给前端,前端接收后用blob进行文件的还原

    代码如下:

    function downloadFile(url, headers, filename) {
    
      function handleFile(data) {
        console.log(this.response || data);
        var file = URL.createObjectURL(this.response || data);
        filename = filename || url.split("/").pop();
        var a = document.createElement("a");
        // if `a` element has `download` property
        if ("download" in a) {
          a.href = file;
          a.download = filename;
          document.body.appendChild(a);
          a.click();
          document.body.removeChild(a);
        } else {
          // use `window.open()` if `download` not defined at `a` element
          window.open(file)
        }
      }
    
      var request = new XMLHttpRequest();
      request.responseType = "blob";
      request.onload = handleFile;
      request.open("GET", url);
      for (var prop in headers) {
        request.setRequestHeader(prop, headers[prop]);
      }
    
      request.send();
    }
    
    downloadFile("/path/to/resource/", {"x-content": "abc"}, "filename.zip")

    3,通过form表单进行下载

    参见:

    https://blog.csdn.net/weixin_33812433/article/details/92508393

    4,如果是excel等文件格式应该还可以通过将数据流在前端形成excel文件的方式进行下载,资料未搜集

  • 相关阅读:
    showModalDialog 页面上GridView的分页问题
    Ibatisnet Quick Start
    frame,iframe,frameset之间的关系与区别
    JS控制彈出窗口
    注册Dll
    ibatis动态查询条件
    前端性能优化之文件按需异步加载
    Redis 实践笔记
    性能测试:Redis千万级的数据量的性能测试
    js控制文本框只能输入中文、英文、数字与指定特殊符号.
  • 原文地址:https://www.cnblogs.com/wangtong111/p/11760207.html
Copyright © 2011-2022 走看看