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

前端之家收集整理的这篇文章主要介绍了js 实现文件下载/文件导出。前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

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

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

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

 

使用Angular方式进行导出:

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

 

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

@H_403_10@ url 下载路径
window.location = url;

 

猜你在找的Angularjs相关文章