I have an Angular application where I just want to download a file.
Up until now, this was my code:
this.fileNavigationService.downloadFile(element).subscribe(result => {
this.generateDownload(result);
});
And my service:
downloadFile(file: FileElement) {
return this.http.get(this.apiUrl + '/downloadFile', { params: file.name, responseType: 'blob' });
}
Now, I wanted to show the progression when I download a file. After looking up online, I came across something quite useful. My service now looks like this:
downloadFile(file: FileElement) {
const req = new HttpRequest('GET', '/downloadFile?path=' + file.name, {
reportProgress: true,
});
return this.http.request(req).subscribe(event => {
if (event.type === HttpEventType.DownloadProgress) {
const percentDone = Math.round(100 * event.loaded / event.total);
console.log(`File is ${percentDone}% downloaded.`);
} else if (event instanceof HttpResponse) {
console.log('File is completely downloaded!');
}
});
}
I can clearly see in my console the progress, however, I have now 2 problems:
if
even though the download appears to reach 100%Property 'subscribe' does not exist on type 'Subscription'.
But I can't seem to find a way to make this works so I can get the progression and my result file.
Do you have any idea or examples to help me on this? Thanks.
Angular Download Link You'll use an anchor tag pointing to the file with the href attribute. The download attribute informs the browser that it shouldn't follow the link but rather download the URL target. You can also specify its value in order to set the name of the file being downloaded.
After some research, I finally managed to solve my issue thanks to this answer.
This is now my service code:
downloadFile(file: FileElement) {
return this.http.get(
this.apiUrl + '/downloadFile',
{
params: file.name,
responseType: 'blob',
reportProgress: true,
observe: 'events',
headers: new HttpHeaders({ 'Content-Type': 'application/json' })
}
);
}
And in my component:
this.fileNavigationService.downloadFile(element).subscribe(result => {
if (result.type === HttpEventType.DownloadProgress) {
const percentDone = Math.round(100 * result.loaded / result.total);
console.log(percentDone);
}
if (result.type === HttpEventType.Response) {
this.generateDownload(result.body);
}
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With