Read image as base64 string using file input, JavaScript, Blazor (server-side) and SignalR

While working on Blazor prototype for Radzen I’ve found a little trick how to enable quck image read as base64 string using <input type="file" />, JavaScript and SignalR.

1. Create new Blazor (server-side) project.

UploadImageBlazor1.png

2. Define readFileAsBase64 JavaScript function in your index.html to read the file input selected file as data url (base64 string):

UploadImageBlazor2.png

window.readFileAsBase64 = (fileInput) => {
	const readAsDataURL = (fileInput) => {
		return new Promise((resolve, reject) => {
			const reader = new FileReader();
			reader.onerror = () => {
				reader.abort();
				reject(new Error("Error reading file."));
			};
			reader.addEventListener("load", () => {
				resolve(reader.result);
			}, false);
			reader.readAsDataURL(fileInput.files[0]);
		});
	};

	return readAsDataURL(fileInput);
};

3. Define file input and img HTML components to select and display the image and execute using JSRuntime readFileAsBase64 function to read the image data:

UploadImageBlazor3.png

<img src="@Picture"  />

<input ref="fileUpload" class="form-control" type="file"
       onchange="@(async (e) => Picture = await JSRuntime.Current.InvokeAsync<string>("readFileAsBase64", fileUpload))" />

@functions{
    ElementRef fileUpload;
    string Picture;
}

4. By default SignalR buffer size is set to 13 kb and to enable read of bigger images go to server project Startup.cs and set ApplicationMaxBufferSize:

UploadImageBlazor4.png

// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
	...
	//app.UseServerSideBlazor<App.Startup>();

	// Set ApplicationMaxBufferSize to enable read of bigger images using JSRuntime. Default is 13 kb.
	app.UseSignalR(route => route.MapHub<BlazorHub>(BlazorHub.DefaultPath, options =>
	{
		options.ApplicationMaxBufferSize = 10 * 1024 * 1024;
	})).UseBlazor<App.Startup>();
}

5. Run the application and select image:

UploadImageBlazor5.png

UploadImageBlazor6.png

Source Code

Enjoy!

by Vladimir Enchev

Radzen Community edition

Last week we released Radzen Community edition: a free version of Radzen that allows developers to create beautiful and responsive web applications.
Read more