Skip to content

Instantly share code, notes, and snippets.

@DamienBraillard
Last active November 28, 2024 09:45
Show Gist options
  • Save DamienBraillard/cc20d07ea6aa20a9f3687f870a529926 to your computer and use it in GitHub Desktop.
Save DamienBraillard/cc20d07ea6aa20a9f3687f870a529926 to your computer and use it in GitHub Desktop.
Angular 2+ Download file from API
import { Http, ResponseContentType } from '@angular/http';
...
constructor(
private http: Http,
) { }
downloadFile() {
return this.http
.get('https://jslim.net/path/to/file/download', {
responseType: ResponseContentType.Blob,
search: // query string if have
})
.map(res => {
return {
filename: 'filename.pdf',
data: res.blob()
};
})
.subscribe(res => {
console.log('start download:',res);
var url = window.URL.createObjectURL(res.data);
var a = document.createElement('a');
document.body.appendChild(a);
a.setAttribute('style', 'display: none');
a.href = url;
a.download = res.filename;
a.click();
window.URL.revokeObjectURL(url);
a.remove(); // remove the element
}, error => {
console.log('download error:', JSON.stringify(error));
}, () => {
console.log('Completed file download.')
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment