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文件的方式进行下载,资料未搜集

  • 相关阅读:
    C#文件操作
    C#Web编程
    WMsg参数常量值
    IIS管理网站浏览
    课程视频网址
    CSS 学习质料
    Centos镜像使用帮助
    apache ab压力测试报错(apr_socket_recv: Connection reset by peer (104))
    How to Configure Nginx for Optimized Performance
    luarocks install with lua5.1 and luajit to install lapis
  • 原文地址:https://www.cnblogs.com/wangtong111/p/11760207.html
Copyright © 2011-2022 走看看