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.


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


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

	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:


<img src="@Picture"  />

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

    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:


// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)

	// 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;

5. Run the application and select image:



Source Code


Leverage Radzen on LinkedIn

Yes, we are on LinkedIn and you should follow us!

Now, you have the opportunity to showcase your expertise by adding Radzen Blazor Studio and Radzen Blazor Components as skills to your LinkedIn profile. Present your skills to employers, collaborators, and clients.

All you have to do is go to our Products page on LinkedIn and click the + Add as skill button.

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