Angular 2从API下载PDF并在View中显示它

时间:2016-02-12 17:22:45

标签: pdf angular

我正在学习Angular 2 Beta。我想知道如何从API下载PDF文件并在我的视图中显示它?我尝试使用以下内容提出请求:

    var headers = new Headers();
    headers.append('Accept', 'application/pdf');
    var options = new ResponseOptions({
        headers: headers
    });
    var response = new Response(options);
    this.http.get(this.setUrl(endpoint), response).map(res => res.arrayBuffer()).subscribe(r=>{
       console.log(r);
    })
  • 请注意,我只使用console.log查看r
  • 的值

但我总是收到以下异常消息:

  

" arrayBuffer()"方法未在Response超类

上实现

是否因为该方法尚未在Angular 2 Beta中准备好?或者我犯了什么错误?

任何帮助将不胜感激。非常感谢你。

10 个答案:

答案 0 :(得分:17)

事实上,HTTP支持尚未实现此功能。

作为一种变通方法,您需要扩展Angular2的BrowserXhr类,如下所述,在基础xhr对象上设置responseTypeblob

import {Injectable} from 'angular2/core';
import {BrowserXhr} from 'angular2/http';

@Injectable()
export class CustomBrowserXhr extends BrowserXhr {
  constructor() {}
  build(): any {
    let xhr = super.build();
    xhr.responseType = "blob";
    return <any>(xhr);
  }
}

然后,您需要将响应有效内容包装到Blob对象中,并使用 FileSaver 库打开下载对话框:

downloadFile() {
  this.http.get(
    'https://mapapi.apispark.net/v1/images/Granizo.pdf').subscribe(
      (response) => {
        var mediaType = 'application/pdf';
        var blob = new Blob([response._body], {type: mediaType});
        var filename = 'test.pdf';
        saveAs(blob, filename);
      });
}

FileSaver 库必须包含在HTML文件中:

<script src="https://cdnjs.cloudflare.com/ajax/libs/FileSaver.js/2014-11-29/FileSaver.min.js"></script>

请参阅此plunkr:http://plnkr.co/edit/tfpS9k2YOO1bMgXBky5Y?p=preview

不幸的是,这将为所有AJAX请求设置responseType。为了能够设置此属性的值,还需要在XHRConnectionHttp类中进行更多更新。

参考文献请参阅以下链接:

修改

在考虑了一点之后,我认为您可以利用分层注入器并仅在执行下载的组件级别配置此提供程序:

@Component({
  selector: 'download',
  template: '<div (click)="downloadFile() ">Download</div>'
  , providers: [
    provide(CustomBrowserXhr, 
      { useClass: CustomBrowserXhr }
  ]
})
export class DownloadComponent {
  @Input()
  filename:string;

  constructor(private http:Http) {
  }

  downloadFile() {
    this.http.get(
      'https://mapapi.apispark.net/v1/images/'+this.filename).subscribe(
        (response) => {
          var mediaType = 'application/pdf';
          var blob = new Blob([response._body], {type: mediaType});
          var filename = 'test.pdf';
          saveAs(blob, filename);
        });
    }
}

此覆盖仅适用于此组件(在引导应用程序时不要忘记删除相应的提供)。下载组件可以像这样使用:

@Component({
  selector: 'somecomponent',
  template: `
    <download filename="'Granizo.pdf'"></download>
  `
  , directives: [ DownloadComponent ]
})

答案 1 :(得分:17)

所以这就是我如何设法让它发挥作用。 我的情况:我需要从我的API端点下载PDF,并将结果作为PDF保存在浏览器中。

为了支持所有浏览器中的文件保存,我使用了FileSaver.js模块。

我创建了一个组件,它将要下载的文件的ID作为参数。 组件 的调用方式如下:

<pdf-downloader no="24234232"></pdf-downloader>

组件本身使用XHR使用 no 参数中给出的数字来获取/保存文件。这样我们就可以避免Angular2 http模块还不支持二进制结果类型这一事实。

现在,不用多说,组件代码:

    import {Component,Input } from 'angular2/core';
    import {BrowserXhr} from 'angular2/http';

    // Use Filesaver.js to save binary to file
    // https://github.com/eligrey/FileSaver.js/
    let fileSaver = require('filesaver.js');


    @Component({
      selector: 'pdf-downloader',
      template: `
        <button
           class="btn btn-secondary-outline btn-sm "
          (click)="download()">
            <span class="fa fa-download" *ngIf="!pending"></span>
            <span class="fa fa-refresh fa-spin" *ngIf="pending"></span>
        </button>
        `
   })

   export class PdfDownloader  {

       @Input() no: any;

       public pending:boolean = false;

       constructor() {}

       public download() {

        // Xhr creates new context so we need to create reference to this
        let self = this;

        // Status flag used in the template.
        this.pending = true;

        // Create the Xhr request object
        let xhr = new XMLHttpRequest();
        let url =  `/api/pdf/iticket/${this.no}?lang=en`;
        xhr.open('GET', url, true);
        xhr.responseType = 'blob';

        // Xhr callback when we get a result back
        // We are not using arrow function because we need the 'this' context
        xhr.onreadystatechange = function() {

            // We use setTimeout to trigger change detection in Zones
            setTimeout( () => { self.pending = false; }, 0);

            // If we get an HTTP status OK (200), save the file using fileSaver
            if(xhr.readyState === 4 && xhr.status === 200) {
                var blob = new Blob([this.response], {type: 'application/pdf'});
                fileSaver.saveAs(blob, 'Report.pdf');
            }
        };

        // Start the Ajax request
        xhr.send();
    }
}

我已将Font Awesome用于模板中使用的字体。我希望组件在获取pdf时显示下载按钮和微调器。

另外,请注意我可以使用 require 来获取fileSaver.js模块。这是因为我正在使用WebPack所以我可以像我想要的那样需要/导入。根据您的构建工具,您的语法可能会有所不同。

答案 2 :(得分:7)

我不认为所有这些黑客都是必要的。我只是使用角度2.0中的标准http服务进行了快速测试,它按预期工作。

/* generic download mechanism */
public download(url: string, data: Object = null): Observable<Response> {

    //if custom headers are required, add them here
    let headers = new Headers();        

    //add search parameters, if any
    let params = new URLSearchParams();
    if (data) {
        for (let key in data) {
            params.set(key, data[key]);
        }
    }

    //create an instance of requestOptions 
    let requestOptions = new RequestOptions({
        headers: headers,
        search: params
    });

    //any other requestOptions
    requestOptions.method = RequestMethod.Get;
    requestOptions.url = url;
    requestOptions.responseType = ResponseContentType.Blob;

    //create a generic request object with the above requestOptions
    let request = new Request(requestOptions);

    //get the file
    return this.http.request(request)
        .catch(err => {
            /* handle errors */
        });      
}


/* downloads a csv report file generated on the server based on search criteria specified. Save using fileSaver.js. */
downloadSomethingSpecifc(searchCriteria: SearchCriteria): void {

    download(this.url, searchCriteria) 
        .subscribe(
            response => {                                
                let file = response.blob();
                console.log(file.size + " bytes file downloaded. File type: ", file.type);                
                saveAs(file, 'myCSV_Report.csv');
            },
            error => { /* handle errors */ }
        );
}

答案 3 :(得分:6)

这是从我能够提出的API下载文件的最简单方法。

import { Injectable } from '@angular/core';
import { Http, ResponseContentType } from "@angular/http";

import * as FileSaver from 'file-saver';

@Injectable()
export class FileDownloadService {


    constructor(private http: Http) { }

    downloadFile(api: string, fileName: string) {
        this.http.get(api, { responseType: 'blob' })
            .subscribe((file: Blob) => {
               FileSaver.saveAs(file, fileName);
        });    
    }

}

从组件类中调用downloadFile(api,fileName)方法。

让FileSaver在终端中运行以下命令

npm install file-saver --save
npm install @types/file-saver --save

答案 4 :(得分:4)

您好,这是一个工作示例。它也适用于PDF! application / octet-stream - 一般类型。 控制器:

public FileResult exportExcelTest()
{ 
    var contentType = "application/octet-stream";
    HttpContext.Response.ContentType = contentType;

    RealisationsReportExcell reportExcell = new RealisationsReportExcell();     
    byte[] filedata = reportExcell.RunSample1();

    FileContentResult result = new FileContentResult(filedata, contentType)
    {
        FileDownloadName = "report.xlsx"
    };
    return result;
}

Angular2:

服务xhr:

import { Injectable } from '@angular/core';
import { BrowserXhr } from '@angular/http';

@Injectable()
export class CustomBrowserXhr extends BrowserXhr {
  constructor() {
      super();
  }

  public build(): any {
      let xhr = super.build();
      xhr.responseType = "blob";
      return <any>(xhr);
  }   
}

安装文件保护程序npm软件包“file-saver”:“^ 1.3.3”,“@ types / file-saver”:“0.0.0”并包含在vendor.ts import'file-saver'中; < / p>

组件btn下载。

import { Component, OnInit, Input } from "@angular/core";
import { Http, ResponseContentType } from '@angular/http';
import { CustomBrowserXhr } from '../services/customBrowserXhr.service';
import * as FileSaver from 'file-saver';

@Component({
    selector: 'download-btn',
    template: '<button type="button" (click)="downloadFile()">Download</button>',
    providers: [
        { provide: CustomBrowserXhr, useClass: CustomBrowserXhr }
    ]
})

export class DownloadComponent {        
    @Input() api: string; 

    constructor(private http: Http) {
    }

    public downloadFile() {
        return this.http.get(this.api, { responseType: ResponseContentType.Blob })
        .subscribe(
            (res: any) =>
            {
                let blob = res.blob();
                let filename = 'report.xlsx';
                FileSaver.saveAs(blob, filename);
            }
        );
    }
}

使用

<download-btn api="api/realisations/realisationsExcel"></download-btn>

答案 5 :(得分:2)

让Virusaver在Angular 5中工作:安装

npm install file-saver --save
npm install @types/file-saver --save

在您的组件中使用import * as FileSaver from "file-saver";

并使用FileSaver。默认而非FileSaver。另存为

.subscribe(data => {
            const blob = data.data;
            const filename = "filename.txt";
            FileSaver.default(blob, filename);

答案 6 :(得分:1)

以下代码适用于在IE和chrome / safari中下载API respone。这里的响应变量是API响应。

注意:来自客户端的http调用需要支持blob响应。

    let blob = new Blob([response], {type: 'application/pdf'});
    let fileUrl = window.URL.createObjectURL(blob);
    if (window.navigator.msSaveOrOpenBlob) {
        window.navigator.msSaveOrOpenBlob(blob, fileUrl.split(':')[1] + '.pdf');
    } else {
        window.open(fileUrl);
    }

答案 7 :(得分:0)

使用C#Web API的工作解决方案,将PDF作为字节数组加载:

C#将PDF加载为字节数组并将其转换为Base64编码的字符串

public HttpResponseMessage GetPdf(Guid id)
{
    byte[] file = GetFile(id);
    HttpResponseMessage result = Request.CreateResponse(HttpStatusCode.OK);
    result.Content = new StringContent("data:application/pdf;base64," + Convert.ToBase64String(file));
    return result;
}

Angular服务获取PDF

getPdf(): Observable<string> {
    return this.http.get(webApiRequest).pipe(
        map(response => {
            var anonymous = <any>response;
            return anonymous._body;
        })
    );
}

组件视图通过绑定到服务响应来嵌入PDF

下面的pdfSource变量是服务返回的值。

<embed [src]="sanitizer.bypassSecurityTrustResourceUrl(pdfSource)" type="application/pdf" width="100%" height="300px" />

有关更多信息,请参见角度DomSanitizer docs

答案 8 :(得分:0)

http
  .post(url, data, {
    responseType: "blob",
    observe: "response"
  })
  .pipe(
    map(response => {
      saveAs(response.body, "fileName.pdf");
    })
  );

答案 9 :(得分:0)

扩展了@ThierryTemplier对Angular 8所做的工作(公认的答案)。

HTML:

<button mat-raised-button color="accent" (click)="downloadFile()">Download</button>

TypeScript:

downloadFile() {
  this.http.get(
    'http://localhost:4200/assets/other/' + this.fileName, {responseType: 'blob'})
    .pipe(tap( // Log the result or error
      data => console.log(this.fileName, data),
      error => console.log(this.fileName, error)
    )).subscribe(results => {
    saveAs(results, this.fileName);
  });
}

来源: