Last active
November 28, 2024 09:45
-
-
Save DamienBraillard/cc20d07ea6aa20a9f3687f870a529926 to your computer and use it in GitHub Desktop.
Angular 2+ Download file from API
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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