如何使用Angular的2+ @ angular / http模块接收blob响应?

内容来源于 Stack Overflow,并遵循CC BY-SA 3.0许可协议进行翻译与使用

  • 回答 (2)
  • 关注 (0)
  • 查看 (334)

我正在尝试从Angular 2应用程序中提供pdf下载

此代码有效:

    var reportPost = 'variable=lsdkjf';

    var xhr = new XMLHttpRequest();

    xhr.open("POST", "http://localhost/a2/pdf.php", true);
    xhr.responseType = 'blob';
    xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");

    xhr.onreadystatechange = function() {//Call a function when the state changes.
        if(xhr.readyState == 4 && xhr.status == 200) {
            var blob = new Blob([this.response], {type: 'application/pdf'});
            saveAs(blob, "Report.pdf");
        }
    }

    xhr.send(reportPost);

但希望使用Angular 2的内置Http客户端。

一些测试代码:

    var headers = new Headers();
    headers.append('Content-Type', 'application/x-www-form-urlencoded');

    this.http.post('http://localhost/a2/pdf.php', reportPost,  {
        headers: headers
        })
        .retry(3)
        // .map( (res:any) => res.blob() ) // errors out
        .subscribe(
          (dataReceived:any) => {
            var blob = new Blob([dataReceived._body], {type: 'application/pdf'});
            saveAs(blob, "Report.pdf");
          },
          (err:any) => this.logError(err),
          () => console.log('Complete')
        );

saveAs函数来自这里:https://github.com/eligrey/FileSaver.js

提问于
用户回答回答于

随着Angular2 final的发布,我们可以定义一个服务例如:

@Injectable()
export class AngularService {

    constructor(private http: Http) {
    }

    download(model: MyModel) { //get file from service
        this.http.post("http://localhost/a2/pdf.php", JSON.stringify(model), {
        method: RequestMethod.Post,
        responseType: ResponseContentType.Blob,
        headers: new Headers({'Content-Type', 'application/x-www-form-urlencoded'})
    }).subscribe(
        (response) => { // download file
            var blob = new Blob([response.blob()], {type: 'application/pdf'});
            var filename = 'file.pdf';
            saveAs(blob, filename);
    });
}

该服务将获得该文件,然后将其提供给用户。

用户回答回答于

With @4.3, @5和HttpClientModule:

this.http.post(`${environment.server}/my/download`,
                data, 
                {responseType: 'blob', observe: 'response'})
              .map( res => ({content: res.body, 
                             fileName: res.headers.get('content-filename')}));

扫码关注云+社区

领取腾讯云代金券