Open files in new tab

Hi, im trying to open files (images and PDFs) in a new tab, when the user click on image (or in a link). Here is my code:

My images was saved in base64 at my DB and the preview is loaded correctly. I researched but not found something that solved my problem. Can you guys help me?



I have this need too.

Hi maybe i can help, i work with MemorySteam so u have to convert the base64 to a byte[] and write it into a stream

The JS func u need (viewFileFromUrl in case u have an url):

async function viewFileFromStream(fileName, contentStreamReference, mimeType) {
	window.URL = window.URL || window.webkitURL;

	const arrayBuffer = await contentStreamReference.arrayBuffer();
	const blob = new Blob([arrayBuffer], { type: mimeType });
	const url = window.URL.createObjectURL(blob);

	const anchorElement = document.createElement('a');
	document.body.appendChild(anchorElement);

	anchorElement.setAttribute("type", "hidden");
	anchorElement.href = url;
	anchorElement.target = "_blank";	
	anchorElement.click();

	anchorElement.remove();
	window.URL.revokeObjectURL(url);
};

async function viewFileFromUrl(url) {
	window.URL = window.URL || window.webkitURL;

	const anchorElement = document.createElement('a');
	anchorElement.setAttribute("type", "hidden");
	anchorElement.href = url;
	anchorElement.target = "_blank";

	document.body.appendChild(anchorElement);
	anchorElement.click();
	anchorElement.remove();
};

Code Behind:

_js is the dependency injection of IJSRuntime.

Hope this can be usefull

Hi @GodzSky , I hope this will help me, but I have a question about how you generated this "stream" or what it would be. i hope you can help me with this.

Something like this (this is not tested)

using (MemoryStream stream = new MemoryStream(file.Size))
{
    byte[] byteArrFile = Convert.FromBase64String(Base64File);
    stream.Write(byteArrFile, 0, byteArrFile.Length);
stream.Position = 0;

    using var streamRef = new DotNetStreamReference(stream);
    await _js.InvokeVoidAsync("viewFileFromStream", file.Name, streamRef, MimeMapping.MimeUtility.GetMimeMapping(file.Name));
}

OR

byte[] byteArrFile = Convert.FromBase64String(Base64File);
MemoryStream stream = new MemoryStream(byteArrFile);
stream.Position = 0;
using var streamRef = new DotNetStreamReference(stream);
await _js.InvokeVoidAsync("viewFileFromStream", file.Name, streamRef, MimeMapping.MimeUtility.GetMimeMapping(file.Name));
1 Like

Thanks a lot mate, this worked fine for me

1 Like