Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to render byte array knowing its content-type using Blazor?

The following code corresponds to a Blazor server-side page:

<pre>
    @page "/ShowFile/{Id:guid}"
    
    //// What to put here to let the browser render the byte array stored on this.Model
    //// Also how to specify the content type of the response?
    
    @code
    {
        [Parameter]
        public Guid Id { get; set; }
    
        private byte[] Model { get; set; }
    
        protected override async Task OnInitializedAsync()
        {
            await base.OnInitializedAsync();
            //// Gets the byte array of a file based on its identifier.
            this.Model = await this.GetFile(this.Id).ConfigureAwait(false); 
        }
    }
</pre>

In ASP.NET MVC I used to do it in the controller action as:

<pre>
    this.Response.ContentType = "application/pdf"; //// Assuming that byte array represents a PDF document.
    await this.Response.Body.WriteAsync(this.Model);
</pre>

What can I do to let the browser to render the byte array in my page based on its content types?

like image 715
Ricardo Sotolongo Avatar asked Sep 03 '26 23:09

Ricardo Sotolongo


1 Answers

@page "/test"
@inject HttpClient Http

@if (!string.IsNullOrEmpty(pdfContent))
{
    <embed src="@pdfContent" width="800px" height="2100px" />
    <iframe src="@pdfContent" width="800px" height="2100px" />
    <object data="@pdfContent" width="500" height="200"></object>
}


@code {
    string pdfContent = "";

    protected async override Task OnInitializedAsync()
    {
        var data = await Http.GetByteArrayAsync("the source you pdf");

        pdfContent = "data:application/pdf;base64,";
        pdfContent += System.Convert.ToBase64String(data);
    }
}

I tried this with client side blazor and it works there. Give it a try with server side.

like image 167
Zsolt Bendes Avatar answered Sep 06 '26 12:09

Zsolt Bendes



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!