Search code examples
javascriptjqueryblazor.net-6.0blazor-server-side

Blazor Server: Convert blob locally stored in browser to Base64 String


I am creating an application in Blazor Server Net 6

I was able to save the image as a blob on the local browser by going through the documentation

https://learn.microsoft.com/en-us/aspnet/core/blazor/images?view=aspnetcore-7.0#stream-image-data

The images are rendering perfectly in the browser Image being rendered after being converted into a blob

The Blob URL looks something like this

blob:https://localhost:7066/94065f17-5b19-47e4-9256-59f3e237a662

Now, I need to read the blob as a base 64 string. I tried to use IHTTPClient as mentioned below

var result=await httpClient.GetStreamAsync(_card.LogoImageDetails.ActualImage);

But, it throws an exception given below enter image description here

Waiting for an efficient solution to solve this issue

Regards

Saad


Solution

  • Here is the solution

    Created JS methods like this:

    const blobToBase64 = async blob => {
        return new Promise((resolve, reject) => {
            const reader = new FileReader();
            reader.onload = () => resolve(reader.result)
            reader.error = (err) => reject(err)
            reader.readAsDataURL(blob)
        })
    }
    
    window.convertBlobURLToBase64 = async (url) => {
        const response = await fetch(url)
        const blob = await response.blob();
        const imageBase64 = await blobToBase64(blob)
        return imageBase64; 
    }
    

    Use JSInterop to get the base 64 string

     private async Task UploadImagesOnBlobAsync()
        {
            var result=await _jsRunTime.InvokeAsync<string>("convertBlobURLToBase64", _card.LogoImageDetails.ActualImage);
        }