Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

angular

rxjs

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

this code works:

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

but i would have liked to use angular 2's built-in Http client.

a little research:

  • angular docs unwritten at time of posting: https://angular.io/docs/js/latest/api/http/ResponseTypes-enum.html
  • not sure if this applies, but the rxjs responseType parameter seems to include only text and json: https://github.com/Reactive-Extensions/RxJS-DOM/blob/master/doc/operators/ajax.md

and some test code:

    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. the saveAs function comes from here: https://github.com/eligrey/FileSaver.js

like image 583
ryanrain Avatar asked Dec 08 '15 06:12

ryanrain


1 Answers

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

like image 186
Sergio Avatar answered Oct 01 '22 12:10

Sergio