Reputation: 23
I have hooked up following code from different blogs and SO as I couldn't find any tutorial for doing this.
What I have to do is to download a file from the REST API using angular and typescript. I do not have the access to the api (only have the url which is like "http://..." and nothing more.
Here is my typescript code:
//Downloading File
// may be located in any component
let options = {
responseType: ResponseContentType.Blob //This has compilation error. Cannot recognize ResponseContentType.Blob
}
// pass options to request
this.http.get(url, options)
let type = "my/mime";
// download the file - retrieve observable
this.http.get(url, options).map((res: Body) => new Blob([res.blob()], { type: type }));
public downloadAttachment(attachment: MediaDownloadFileDto): void {
this.myDownloadService.downloadFile(downloadUrl, mimeType).subscribe((fileBlob: Blob) => {
fileSaver.saveAs(fileBlob, attachment.filename);
}, (message: string) => {
// error handling...
});
}
// may be located in any service:
public downloadFile(url: string, type: string): Observable<Blob> {
let options = {
responseType: ResponseContentType.Blob
};
return this.http.get(url, options).map((res: Body) => new Blob([res.blob()], { type: type }));
}
Here is the HTML Button I am using:
<button class="nui-button nui-button--alt download" (click)="downloadFile(url,options)">Download Template</button>
Thanks
Upvotes: 2
Views: 3379
Reputation: 7145
You can simply use the HTML download
attribute.
Try this:
<a href="https://some-rest-api.com/some-file.mp4" download>
Upvotes: 1