Reputation: 1554
The only way of getting the image in browser is opening it in a new window. But i want the browser to download it. I migrated to the new HttpClient and now i can't seem to do it.
I have searched online and the two options are:
Making an anchor element with display: none
and dynamically adding the url to the href. But then i have to use the DOMSanitizer with bypassSecurityTrustUrl()
and this is a security risk, so i can't use this.
OR
Use the filesave.js package, but in our project we want to try and avoid packages and it uses RAM so for big files it's no options. Streamsaver.js is not supported in FF and edge so also no option.
I used to do it like this with the old HTTP module of Angular < 4, and it would just download it no questions asked:
const subscription = this.downloadService.downloadFile(id, this.file.folderId).subscribe(data => {
window.location.href = data.url;
subscription.unsubscribe();
}, error => {
console.log(error);
});
Now i do it like this but it opens a new tab, which in Chrome gets blocked automatically:
const sub = this.downloadService.downloadFile(downloadArray, this.folders.id).subscribe(data => {
const blob = new Blob([data], { type: 'image/png' });
const blobUrl = window.URL.createObjectURL(blob);
const winOpen = window.open(blobUrl);
sub.unsubscribe();
}, error => {
console.log(error);
});
So just want it do to something like this:
window.download(blobUrl);
And be done with it. Why is this so hard? Are there security issues or something? I dont really understand.
Upvotes: 1
Views: 143
Reputation: 3181
After a lot of struggle, I found the problem, for me at least. I was using an ad-blocker plugin (uBlock origin), which apparently blocks blob URLs. In fact, it seems that all ad-blockers do this by default. Disabling the ad-blocker on my localhost (or whatever website you deploy to) solved the issue for me.
You can read more about it here: Why Do Ad Blockers Block Blobs?
Upvotes: 1