zoukankan      html  css  js  c++  java
  • 文件下载方法

    通常来说,我们工作中遇到的都是get方式进行文件下载,只需要window.open打开链接就可以进行自动下载,下载所需要的参数只需要跟在链接后面即可

    但是偶尔会遇到要求post请求进行下载文件,有可能是因为参数过多,也可能需要隐藏参数

    通过ajax的方式或者fetch的方式请求文件下载链接会发现会接到文件流,最后把文件信息请求回来,但是无法实现下载功能,这个时候只能通过form提交的方式进行下载

    但是form提交会导致页面进行跳转,大多数场景并不需要这种提交方式,所以我们需要一个iframe来进行form提交,跳转的时候就不会影响当前页面,再将iframe隐藏起来。

    /*
    * options(Object) 配置项
    ** method(String) 提交模式,默认post
    ** url(String)  提交路径,必须
    ** data(Object)  提交参数,以键值对方式进行匹配
    */
    function downLoadFile (options) {
    var config = Object.assign({}, {
            method: 'post'
          }, options);
          if (!window.frames["down-file-iframe"]) {
            let ifa = document.createElement('iframe');
            ifa.id = ifa.name = 'down-file-iframe';
            document
              .body
              .appendChild(ifa);
          }
          var $form = `<form target="down-file-iframe" method="${config.method}" action="${config.url}" id="down-file-form" />`;
          for (var key in config.data) {
            $form += `<input type="hidden" name="${key}" value="${config.data[key]}" />`;
          }
          $form += `</form>`;
          window.frames["down-file-iframe"].document.body.innerHTML = $form;
          window
            .frames["down-file-iframe"]
            .document
            .getElementById("down-file-form")
            .submit();
            alert('文件正在下载,可能需要较长时间,请稍后!');
        }

    使用了部分模板字符串,需要兼容的话,可以调整为es5的语法

  • 相关阅读:
    var、let、const之间的区别
    es5和es6的区别
    [2020CCPC威海G] Caesar Cipher
    [CF1437E] Make It Increasing
    [CF1437C] Chef Monocarp
    [CF1436D] Bandit in a City
    [CF1418D] Trash Problem
    [CF1419E] Decryption
    [CF1420C2] Pokémon Army (hard version)
    [CF1424M] Ancient Language
  • 原文地址:https://www.cnblogs.com/timmer/p/8554774.html
Copyright © 2011-2022 走看看