当前位置:  开发笔记 > 编程语言 > 正文

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

如何解决《如何使用Angular的2+@angular/http模块接收blob响应?》经验,为你挑选了2个好方法。

我正试图从一个有角度的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客户端.

一点研究:

发布时未写入的角度文档:https: //angular.io/docs/js/latest/api/http/ResponseTypes-enum.html

不确定这是否适用,但rxjs responseType参数似乎只包含text和json:https: //github.com/Reactive-Extensions/RxJS-DOM/blob/master/doc/operators/ajax.md

和一些测试代码:

    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')
        );

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



1> Sergio..:

随着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);
            },
            error => {
                console.error(`Error: ${error.message}`);
            }
        );
    }
}

此服务将获取该文件,然后将其提供给用户.

zip文件示例:如何使用JAX-RS和Angular 2+下载zip文件


从'@ angular/http'导入{ResponseContentType};
谢谢 !我错过了responseType:ResponseContentType.Blob.
我得到这个错误`[ts]属性'blob'在'Blob'类型上不存在.有谁知道为什么?

2> sabithpocker..:

使用@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')}));

推荐阅读
黄晓敏3023
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有