【问题标题】:Download a file in Angular 2在 Angular 2 中下载文件
【发布时间】:2017-11-10 20:27:48
【问题描述】:

我想在 Angular 2 中下载 pdf 格式的文件,我正在使用 FileSaver.js 将文件另存为 pdf。

(response) => {
    var mediaType = 'application/pdf';
    let pdfContent = response["_body"];

    var blob = new Blob([pdfContent], {type: mediaType});
    var filename = 'test.pdf';
    //setTimeout(FileSaver.saveAs(blob, filename),10000); //Tried this but no result
    //  FileSaver.saveAs(blob(), "docitt-report-" + documentNo + ".pdf"); //tried this too
  },

但是下载的 pdf 文件是空的,我想可能是资源需要时间所以我尝试了setTimeout,但它仍然没有帮助。尽管响应中有数据,我可以在控制台中看到response._body

让我知道我哪里出错了。

【问题讨论】:

标签: javascript angular filesaver.js


【解决方案1】:

我得到了它的工作,这是我的答案:

downloadDocument(docId){
  const headers = new Headers({responseType:ResponseContentType.Blob});
  headers.append('authorization','Bearer '+token);
  this.http.get(url,{headers:headers,responseType:ResponseContentType.Blob}).subscribe(
    (response) => {    
     FileSaver.saveAs(response.blob(), "Document-" + docId+ ".pdf");
    }
  );
}

导入 FilSaver

import * as FileSaver from 'file-saver';

【讨论】:

    【解决方案2】:

      import 'rxjs/Rx' ;
    
    
    
    
    this._reportService.getReport().subscribe(data => this.downloadFile(data)),//console.log(data),
                     error => console.log("Error downloading the file."),
                     () => console.info("OK");
                     
       When the request is ready it will call the function "downloadFile" that is defined as follows
    downloadFile(data: Response){
      var blob = new Blob([data], { type: 'text/csv' });
      var url= window.URL.createObjectURL(blob);
      window.open(url);
    }

    【讨论】:

      猜你喜欢
      • 2018-03-06
      • 1970-01-01
      • 1970-01-01
      • 2017-09-29
      • 1970-01-01
      • 2018-05-30
      • 2018-05-26
      • 2018-08-12
      • 1970-01-01
      相关资源
      最近更新 更多