How to receive blob responses using Angular's 2+ @angular/http module?

后端 未结 3 1390
暖寄归人
暖寄归人 2020-12-02 16:09

I\'m trying to provide a pdf download from within an angular 2 app...

this code works:

    var reportPost = \'variable=lsdkjf\';

    var xhr = new X         


        
相关标签:
3条回答
  • 2020-12-02 16:16

    With @4.3, @5 and HttpClientModule, I ended up doing:

    this.http.post(`${environment.server}/my/download`,
                    data, 
                    {responseType: 'blob', observe: 'response'})
                  .map( res => ({content: res.body, 
                                 fileName: res.headers.get('content-filename')}));
    
    0 讨论(0)
  • 2020-12-02 16:21

    See here: https://stackoverflow.com/a/45666313/4420532

    return this._http.get('/api/images/' + _id, {responseType: 'blob'}).map(blob => {
      var urlCreator = window.URL;
      return this._sanitizer.bypassSecurityTrustUrl(urlCreator.createObjectURL(blob));
    })
    
    0 讨论(0)
  • 2020-12-02 16:33

    With the release of Angular2 final we can define for example a service:

    @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}`);
                }
            );
        }
    }
    

    This service will get the file and then serve it to an user.

    Example for zip file: How to use JAX-RS and Angular 2+ to download a zip file

    0 讨论(0)
提交回复
热议问题