Angular 2 file download: corrupted result

I am trying to upload a file using Angular 2 / TypeScript and the web API. The problem I am experiencing is that when downloading a text file, the file is a file, but when you try to download a PDF file, for example, it is damaged. The contents of the downloaded file is garbage.

TypeScript I use the following:

downloadFile(fileId: string): Observable<File> { this.applicationsUrl = `${APIConfig.BaseUrl}/documents/download/${fileId}/`; let headers = new Headers({ 'Content-Type': 'application/json', 'MyApp-Application' : 'AppName' }); let options = new RequestOptions({ headers: headers }); return this.http.post(this.applicationsUrl, '', options) .map(this.extractContent) .catch(this.handleError); } private extractContent(res: any) { let blob: Blob = new Blob([res._body], { type: 'application/pdf'}); window['saveAs'](blob, 'test.pdf'); } 

The ['saveAs'] window is just a workaround to access JavaScript functions in FileSaver.js.

In addition, I set res: Response to res: any, so I can access my own _body property under JavaScript without compilation failure in TypeScript.

Any help would be greatly appreciated.

+6
angular typescript
Aug 05 '16 at 16:25
source share
1 answer

As of Angular RC5, the following code should work for you:

 downloadFile(fileId: string): Observable<File> { this.applicationsUrl = `${APIConfig.BaseUrl}/documents/download/${fileId}/`; let headers = new Headers({ 'Content-Type': 'application/json', 'MyApp-Application' : 'AppName', 'Accept': 'application/pdf' }); let options = new RequestOptions({ headers: headers, responseType: ResponseContentType.Blob }); return this.http.post(this.applicationsUrl, '', options) .map(this.extractContent) .catch(this.handleError); } private extractContent(res: Response) { let blob: Blob = res.blob(); window['saveAs'](blob, 'test.pdf'); } 

I had a similar problem and installing Accept-Header on application/pdf , responseType on Blob and accessing blob through the corresponding Method on Response resolved this for me :) (I also use FileSaver)

+8
Sep 13 '16 at 13:51
source share



All Articles