JS 解决 window.location.href 下载文件时,一次点击产生两次下载+页面跳转问题

请求被覆盖,原来代码

function download(url){
 window.open(url);
}

没有后端配合的情况下改成

function download(url){
  //获得id为downLoadListFrame的frame
  var divFrame = window.parent.document.getElementById("downLoadListFrame")
  //判断是否存在,如果存在先移除,再重新创建
  if (divFrame != null) {
      window.parent.document.body.removeChild(divFrame)
  }
  //重新创建
  var iframe = window.parent.document.createElement("iframe");
  iframe.setAttribute("id", "downLoadListFrame");
  //download_file.id = "downFrame";
  window.parent.document.body.appendChild(iframe);
  divFrame = window.parent.document.getElementById("downLoadListFrame");
  //隐式调用,(注意:window.parent.document 适应对于,farme内部代码,调用frame 外部dom;如果项目未用frame,改写成 document即可)
  divFrame.src = url;
  divFrame.style.display = "none";
}

如果请求后端接口去下载文件流的方式

function download(params, downloadName, url,type){
  let that = this;
  let data = params;
  let xhttp = new XMLHttpRequest();
  xhttp.onreadystatechange = function () {
    let a;
    if (xhttp.readyState === 4 && xhttp.status === 200) {
      // for ie 10+
      if (window.navigator.msSaveBlob) {
        window.navigator.msSaveOrOpenBlob(xhttp.response, downloadName);
        return;
      }
      a = document.createElement('a');
      a.href = window.URL.createObjectURL(xhttp.response);
      a.download = downloadName;
      a.style.display = 'none';
      document.body.appendChild(a);
      a.click();
    }
  };
  let mothed = type?type:'POST';
  xhttp.open(mothed, process.env.VUE_APP_BASE_API + url);
  xhttp.setRequestHeader("Content-Type", "application/json");
  xhttp.setRequestHeader("token", getToken() || ''); //根据实际情况是否要加token
  xhttp.responseType = 'blob';
  xhttp.send(JSON.stringify(data));
}

params入参, downloadName名称,, downloadUrl下载地址,type请求类型get/post

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容