I know it is a dumb question but can someone tell me how can I prompt the user to download a file that is sent by the backend in the response?
You have two possibilities:
If the backend sends the file directly to the browser by clicking a link then the backend should use the content type application/octet-stream in the headers. That causes the browser to ask the user how to save/open the file.
If you load the file from the backend through Angular code (Http Module) then you could use filesaver.js or a similar library. Then you have the full control and can prompt the user yourself.
npm install file-saver --save
... and the typings:
npm install @types/file-saver --save-dev
The code in the service:
public getFile(path: string):Observable<Blob>{ let options = new RequestOptions({responseType: ResponseContentType.Blob}); return this.http.get(path, options) .map((response: Response) => <Blob>response.blob()) .catch(this.handleError); }
For using FileSaver.js put the following import to your component:
import * as FileSaver from 'file-saver';
To trigger the download use that:
this.api.getFile("file.pdf") .subscribe(fileData => FileSaver.saveAs(fileData, "file.pdf"));
1.4m articles
1.4m replys
5 comments
57.0k users