JS文件下载,文件下载页面跳转出现空白页解决办法

712 阅读1分钟

文件下载出现空白页或页面跳转,是因为直接用文件地址跳转window.open或者location.href这种方式会有页面跳转的情况出现。

下面看怎么解决这个问题

例子

方案一(推荐):用js触发<a>标签点击事件

    var downLoad=function(src){
      var a = document.createElement('a');
      a.id = 'expertFile'
      a.href =src;
      document.body.append(a); 
      a.click();
      document.getElementById('expertFile').remove();
    }
    downLoad()
方案二:通过[iframe]来下载,

有网友说会有下载两次的情况,我自己试没发现这个问题,你们要是遇到这个问题可以用第一种方法哦~

//传入参数src为文件地址

    function  download (src) {
       var download_file= {} 
      if (typeof(download_file.iframe) == "undefined") {
        var iframe = document.createElement("iframe");
        download_file.iframe = iframe;
        document.body.appendChild(download_file.iframe);
      }
      download_file.iframe.src = src
     download_file.iframe.style.display = "none";
    },

原文链接:blog.csdn.net/weixin_3941…