Thursday, October 2, 2025

Blazor Disconnects When Uploading a File

The InputFile control in Blazor is finicky.  The entire application shuts down locally after attempting to upload a file.  When deployed, the session resets.  What are some reasons why this happens?

1.  There is a breakpoint set your file upload method.  Believe it or not, the application will completely shut down if you just have a breakpoint set when running locally.

2.  The file is being read into memory and then performing some processing on it and then saving it to a file.  The InputFile expects to immediately save the file to disk without any waiting.

3.  The max file size is less than the size of the file.

4.  The Blazor signal R receive size is less than the size of the file.

I had a requirement to remove the Geolocation from large images, resize it to a maximum of 1000 pixels width or height, and convert to webp.  All of these things came into consideration.

In your program.cs ensure you have set the MaximumReceiveMessageSize to the largest file you will have.  In the example below it is 300MB

builder.Services.AddSignalR(o => { o.MaximumReceiveMessageSize = 300 * 1024 * 1024; });

Here is how to define an inputfile

<InputFile id="fileUpload" hidden OnChange="HandleFileUpload" multiple accept="@String.Join(',',AllowedExtensions)" />

This is the code behind for handling the upload.

public int MaxFileSize { get; set; } = 300 * 1024 * 1024;
public string CurrentFolderPath { get; set; }
public List<string> AllowedExtensions { get; set; } = new List<string>()
{
".jpg", ".jpeg", ".png", ".gif", ".webp", ".svg"
};
private async Task HandleFileUpload(InputFileChangeEventArgs e)
{
try
{
if (e == null) return;
IReadOnlyList<IBrowserFile> inputFiles = e.GetMultipleFiles();
foreach (var file in inputFiles)
{
if (!await HandleSingleFile(file)) return;
}
//Do your other processing here after the files have been saved
foreach (var file in inputFiles)
{
}
}
catch (Exception ex)
{
Log.Error(ex, "Failed to upload files to {CurrentFolderPath}", CurrentFolderPath);
ErrorMessage = $"Failed to upload: {ex.Message}";
}
finally
{
StateHasChanged();
}
}
private async Task<bool> HandleSingleFile(IBrowserFile file)
{
var targetPath = Path.Combine(CurrentFolderPath, file.Name);
if (!AllowedExtensions.Contains(Path.GetExtension(file.Name)))
{
ErrorMessage = $"File type not allowed for {file.Name}. Valid File Types are:<br />" +
String.Join("<br />", AllowedExtensions);
return false;
}
if (file.Size > MaxFileSize)
{
ErrorMessage = $"File size exceeds the maximum limit of {MaxFileSize / 1024.0 / 1024.0:F2} MB for for {file.Name}.");
return false;
}
using (var targetStream = new FileStream(targetPath, FileMode.Create))
{
using (var fileStream = file.OpenReadStream(MaxFileSize))
{
await fileStream.CopyToAsync(targetStream);
}
}
return true;
}

See the full implementation of uploading a file, removing the GeoLocation, resizing and converting to .webp here:

No comments:

Post a Comment