2015-12-08 10 views
17

Sto cercando di fornire una scarica il pdf dall'interno di un angolare 2 app ...Come ricevere le risposte BLOB utilizzando il modulo Angular 2+ @ angular/http?

questo codice funziona:

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

ma mi sarebbe piaciuto usare client HTTP integrato angolare 2 di.

una piccola ricerca:

e qualche codice di prova:

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

grazie!

ps. la funzione saveAs viene da qui: https://github.com/eligrey/FileSaver.js

+1

sembra il blob() - Metodo ISN 'ancora implementato. Vedere https://github.com/angular/angular/blob/master/modules/angular2/src/http/static_response.ts#L89. Un problema che tiene traccia dello stato di implementazione può essere trovato qui: https://github.com/angular/angular/issues/2803 – Larrifax

+0

In che modo hai avuto "saveAs" per funzionare? Ho installato il modulo, installato le tipizzazioni, e ancora ottengo "nessuna funzione del genere: saveAs" quando lo eseguo .. mooolto fastidioso ... come lo includi nel codice dattiloscritto? (Io uso il webpack, non l'ho ancora capito) – Spock

+1

Ho appena ignorato l'errore dal compilatore TS. compila ancora ... sciatto eh? – ryanrain

risposta

39

Con il rilascio di Angular2 finale possiamo definire ad esempio un servizio:

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

Questo servizio otterrà il file e poi servire a un utente.

Esempio di file zip: How to use JAX-RS and Angular2 to download a zip file

+3

grazie! ho perso la rispostaTipo: ResponseContentType.Blob. – gal

+1

qualcuno può contrassegnare questo come la risposta corretta per favore, ho cercato questo da secoli. – arvstracthoughts

+2

import {ResponseContentType} da '@ angular/http'; –

6

Con @4.3, @5 e HttpClientModule, ho finito per fare:

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

vedere qui: 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)); 
})