Search code examples
c#blazor-webassembly

How to open a File stream in new tab in Blazor Web Assembly?


I have scenario, where i have a API, which will return FileStream(with Content Type application/pdf). On Button click i need to call the API & get the file stream & open the stream in a New Tab.

have tried "IJsRuntime". but below code seems not working. Is there any other way to handle this?

jsRuntime.InvokeVoidAsync("open", "File_Stream", "_blank")

I am new to Blazor.


Solution

  • I have tried from my side. Below approach worked for me.

    In Razor page add required button or label & add the Onclick eventHandler code along with Injection with IjsRuntime.

    @inject IJSRuntime JSRuntime
    
    <button @onclick="GetFilecontent">Click Here</button>
    
    
    @code {
    
        private async Task GetFilecontent() 
        {
            var result = await Http.GetAsync("api/getFileBytes"); //Output should be FileContent
            var FileStream = result.Content.ReadAsByteArrayAsync().Result.ToArray();
            await JSRuntime.InvokeVoidAsync("openInNewTab",FileStream);
        }
    }
    

    openInNewTab is the Js function which will take the File stream & will render in a new tab with the File Array.

    Create a HTML file , where the File will render.

        <script src="_framework/blazor.webassembly.js"></script>
        <script>
            function openInNewTab(array) {
                // Create a Blob object from the array
                var file = new Blob([array], { type: 'application/pdf'});
                // Create a URL for the Blob
                var fileURL = URL.createObjectURL(file);
                // Open the URL in a new tab
                window.open(fileURL, '_blank');
            }
        </script>
    

    File will open in new window.