Reputation: 161
Sorry if there is another post talking about this, but I can't find it and it's driving me crazy.
I made a webservice that returns a file in form of a byte array, and it works fine. After that,
On the other side, I'm developing an Angular 4 site that calls de webservice mentioned and try to download the obtained file. So I came up with the following code:
downloadFile() {
let theFile;
this.http.get(FILE_DOWNLOAD_ENDPOINT, { responseType: 'blob' })
.subscribe(data => {
theFile = new Blob([data], { type: 'application/octet-stream' });
let url = window.URL.createObjectURL(theFile);
console.log(url);
const link = document.createElement('a');
link.href = url;
link.download = 'file.pdf';
console.log(link);
link.click();
},
error => {
console.log(error);
},
() => console.log('File download completed.'));
}
This code works as expected using Chrome, but Internet Explorer doesn't download the file to the browser.
Thanks to console.log()
I can see that the link element created is different:
Could anybody help me? Thanks a lot in advance!!
Upvotes: 0
Views: 1989
Reputation: 161
Finally, I found this similar post. I modified my function and now look like this (it works perfectly now both in Chrome and IE11):
downloadFile() {
let theFile;
this.http.get(FILE_DOWNLOAD_ENDPOINT, { responseType: 'blob' })
.subscribe(data => {
theFile = new Blob([data], { type: 'application/octet-stream' });
if (window.navigator && window.navigator.msSaveOrOpenBlob) {
window.navigator.msSaveOrOpenBlob(theFile, 'file.pdf');
} else {
const url = window.URL.createObjectURL(theFile);
window.open(url);
const link = document.createElement('a');
link.href = url;
link.download = 'file.pdf';
link.click();
}
},
error => {
console.log(error);
},
() => console.log('File download completed.'));
}
Thank you!
Upvotes: 1
Reputation: 8859
I had to implement same feature for my app and I used this library: File-Saver
It has come quiet handy.
Upvotes: 1