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 = () => {
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:
<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:
// 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:
Enjoy!