Currently in my web application, which utilizes Angular for the front-end and .Net Core for the back-end, there is a page where users can click on server-side stored files. The desired behavior is for the file to open directly in a new tab if the browser allows (e.g., text, images, PDF). If not permitted by the browser, the file should be downloaded instead.
The code snippet from my Angular implementation looks like this:
openFile(fileId: string, name: string) {
this.httpClient.get('Attachments/Download/' + fileId, { responseType: 'arraybuffer', headers: { 'Content-Type': 'text/plain' }, observe: 'body' }).subscribe(file => {
if (!file) {
console.error("file not found.");
return;
}
this.http.get<string>('File/MimeType/' + encodeURIComponent(name)).subscribe(mimetype => {
if (!mimetype || mimetype === '') {
console.error("mimetype not found.");
} else {
const blob = new Blob([file], { type: mimetype });
const url = window.URL.createObjectURL(blob);
window.open(url, '_blank');
}
});
});
}
Although it functions correctly, the use of window.URL.createObjectURL(blob)
leads to file names being replaced with an ID format (e.g.,
blob:http://my-site/8b92c1b8-72e9-461c-b66c-40a65e705591
). I am aware of alternative methods such as using an <a>
tag with the download
attribute (which preserves the original file name but does not allow direct opening in the browser).
The goal is for the browser to determine the appropriate action whenever possible. Any suggestions or solutions are appreciated. Thank you in advance. :)
EDIT: I welcome suggestions that involve utilizing only the backend (.Net Core) as long as the file still opens in a new tab.