加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

js 实现文件下载/文件导出。

发布时间:2020-12-17 16:55:26 所属栏目:安全 来源:网络整理
导读:1. POST方式进行文件导出; // url 下载URL fileName 下载文件名称 function exportFile(url,fileName) { let xhr = new XMLHttpRequest(); xhr.open( "POST" ,url); xhr.responseType = "blob" ; xhr.onload = () = { let ctx = xhr.response; let blob = B

1. POST方式进行文件导出;

  // url 下载URL
   fileName 下载文件名称
  function exportFile(url,fileName) {
    let xhr = new XMLHttpRequest();
    xhr.open("POST",url);
    xhr.responseType = "blob";
    xhr.onload = () => {
      let ctx = xhr.response;
      let blob =  Blob([ctx]);
      if ("msSaveOrOpenBlob" in navigator) {兼容IE
        window.navigator.msSaveOrOpenBlob(blob,fileName);
      } else {
        let aLink = document.createElement("a");
        aLink.download = fileName;
        aLink.style.display = "none";
        aLink.href = URL.createObjectURL(blob);
        document.body.appendChild(aLink);
        aLink.click();
        document.body.removeChild(aLink);
      }
    };
    xhr.send();
  }

使用方法:exportFile(url,fileName);

?

使用Angular方式进行导出:

class ExportEvent {
      constructor( private http:HttpClient ){}
         url 下载URL
         fileName 下载文件名称
      exportFile(url,fileName){
            this.http.request("POST",url,{},{responseType:"blob"}).pipe()
       .subscribe( (res)
=>{ let blob = Blob([res]); window.navigator.msSaveOrOpenBlob(blob,fileName); } { let aLink = document.createElement("a"); aLink.download = fileName; aLink.style.display = "none"; aLink.href = URL.createObjectURL(blob); document.body.appendChild(aLink); aLink.click(); document.body.removeChild(aLink); } },(error)=>{ let reader = FileReader(); reader.onload = (e)=>{ if(e && e["target"]){ let errorMsg = JSON.parse(e["target"]["result"]); if(errorMsg && errorMsg["code"]){ console.log("有报错,出错了。。。。。"); } } } error.error的值是一个Blob对象 reader.readAsText(error.error); }
       ); } }

?

2. GET方式进行文件导出;

 url 下载路径
window.location = url;

?

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读