首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何使用angular的2+ @angular/http模块接收blob响应?

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

Stack Overflow用户
提问于 2015-12-08 14:53:30
回答 3查看 81.2K关注 0票数 31

我正在尝试从angular 2应用程序中提供一个pdf下载...

下面的代码可以工作:

代码语言:javascript
复制
    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客户端。

一个小小的研究:

rxjs

参数似乎只包含和json:

  • :responseType

和一些测试代码:

代码语言:javascript
复制
    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

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2016-09-26 03:15:32

随着Angular2最终版的发布,我们可以定义一个服务:

代码语言:javascript
复制
@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}`);
            }
        );
    }
}

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

压缩文件示例:How to use JAX-RS and Angular 2+ to download a zip file

票数 54
EN

Stack Overflow用户

发布于 2017-10-30 20:44:40

对于@4.3, @5HttpClientModule,我最终做了:

代码语言:javascript
复制
this.http.post(`${environment.server}/my/download`,
                data, 
                {responseType: 'blob', observe: 'response'})
              .map( res => ({content: res.body, 
                             fileName: res.headers.get('content-filename')}));
票数 16
EN

Stack Overflow用户

发布于 2017-11-07 22:58:16

查看此处:https://stackoverflow.com/a/45666313/4420532

代码语言:javascript
复制
return this._http.get('/api/images/' + _id, {responseType: 'blob'}).map(blob => {
  var urlCreator = window.URL;
  return this._sanitizer.bypassSecurityTrustUrl(urlCreator.createObjectURL(blob));
})
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/34149741

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档