前端实现文件下载总结

发布时间:2023-05-04 08:30

1.通过js 创建 a 标签方法
sUrl可以是服务中的相对路径



export(sUrl){
//iOS devices do not support downloading. We have to inform user about this.
  if (/(iPhone)/g.test(navigator.userAgent)) {
    alert("Your device does not support files downloading. Please try again in desktop browser.");
    return false;
  }

  //If in Chrome or Safari - download via virtual link click
  if (downloadFile.isChrome || downloadFile.isSafari || downloadFile.isFirefox) {
    //Creating new link node.
    var link = document.createElement("a");
    link.href = sUrl;
    link.target = "_blank";

    if (link.download !== undefined) {
      //Set HTML5 download attribute. This will prevent file from opening if supported.
      var fileName = sUrl.substring(sUrl.lastIndexOf("/") + 1, sUrl.length);
      link.download = fileName;
    }
    
    //Dispatching click event.
    if (document.createEvent) {
      var e = document.createEvent("MouseEvents");
      e.initEvent("click", true, true);
      link.dispatchEvent(e);
      return true;
    }
  }
  
  // Force file download (whether supported by server).
  if (sUrl.indexOf("?") === -1) {
    sUrl += "?download";
  }
  
  window.open(sUrl, "_self");
  return true;
}

downloadFile.isChrome = navigator.userAgent.toLowerCase().indexOf("chrome") > -1;
downloadFile.isSafari = navigator.userAgent.toLowerCase().indexOf("safari") > -1;
downloadFile.isFirefox = navigator.userAgent.toLowerCase().indexOf("firefox") > -1;

2.在模板template中直接定义a 标签
file_path 必须是绝对路径

  1. 利用当前页面打开链接路径 location.href
    sUrl 必须是绝对路径

    
    
    export(sUrl){
     window.location.href = sUrl
    
    }

4.利用window.open, 打开浏览器一个窗口
sUrl 必须是绝对路径



export(sUrl){
   window.open(sUrl, "_self")
}

ItVuer - 免责声明 - 关于我们 - 联系我们

本网站信息来源于互联网,如有侵权请联系:561261067@qq.com

桂ICP备16001015号