I have requirement to get the blob response from backend service, process that response and open the file in new tab with custom name using Angular. This is the code that I have written so far:
HTTP Request
return this.http.get(url, { responseType: 'blob' });
Processing Response
const blob = new Blob([fileResponseData], { type: 'application/pdf' });
const fileName = this.getFileName();
// IE Browser
if (window.navigator && window.navigator.msSaveOrOpenBlob) {
window.navigator.msSaveOrOpenBlob(blob, fileName);
return;
}
// Other Browsers
const url = window.URL.createObjectURL(blob);
const link = this.renderer.createElement('a');
this.renderer.setAttribute(link, 'download', fileName);
this.renderer.setAttribute(link, 'href', url);
this.renderer.setAttribute(link, 'target', '_blank');
this.renderer.appendChild(this.elementRef.nativeElement, link);
link.click();
this.renderer.removeChild(this.elementRef.nativeElement, link);
setTimeout(() => {
window.URL.revokeObjectURL(url);
}, 1000);
While this solution does downloads the file with custom name but it does not opens the blob URL in new tab. The file gets downloaded in the same tab!
After going through some solutions on Stack Overflow, I came across the information that target = _blank may not work with blob URL if you have AD-Blockers on, I did verified that and I don't have any ad-blockers, yet I am not able to open this file in new tab!
Alternative solution was:
const url = window.URL.createObjectURL(blob);
window.open(url, '_blank');
With this solution, the file opens in new tab but I was not able to find any work-around to assign it with a custom name.
I need help with:
- on click - opening the (blob) file in tab
- on download - file should have custom name