Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Blazor UI hanging during memory file upload

I'm working on a simple blazor application that receives a file upload and stores it. I am using BlazorInputFile and I can't work out why copying the stream to MemoryStream is causing the browser to freeze.

The details of how to use (and how it's implemented) BlazorInputFile are explained in this blog post: Uploading Files in Blazor.

 var ms = new MemoryStream();
 await file.Data.CopyToAsync(ms); // With a 1MB file, this line took 3 seconds, and froze the browser

 status = $"Finished loading {file.Size} bytes from {file.Name}";

Sample project/repo: https://github.com/paulallington/BlazorInputFileIssue (this is just the default Blazor app, with BlazorInputFile implemented as per the article)

like image 767
Paul Avatar asked Sep 19 '25 16:09

Paul


2 Answers

Use await Task.Delay(1); as mentioned on Zhi Lv's comment in this post blazor-webassembly upload file can't show progress?

var buffer = new byte[imageFile.Size];
await Task.Delay(1);

await imageFile.OpenReadStream(Int64.MaxValue).ReadAsync(buffer);

pratica.Files.Add(new FilePraticaRequest()
{
    Contenuto = buffer,
    Nome = imageFile.Name,

});
StateHasChanged();
like image 55
Davide Camerlingo Avatar answered Sep 22 '25 07:09

Davide Camerlingo


I've experienced the same issue. I've tried both predefined components such as Steve Sanderssons file upload and MatBlazor fileupload and also my own component to handle fileuploads. Small files are not a problem. Once the files are a bit larger in size the UI will hang itself. MemoryOutOfBoundsException (or similar). So no, async/await can't help you release the UI. I have put so much effort into this issue, one solution, that I am currently using, is to do all fileuploads with javascript instead of blazor. Just use javascript to get the file and post it up to the server. No JSInterop.. However, it seems like it is a memory issue in webassembly mono. Read more here: https://github.com/dotnet/aspnetcore/issues/15777

Note: I haven't tried this on the latest Blazor version. So I'm not sure it's fixed or not.

like image 35
LordSilvermort Avatar answered Sep 22 '25 07:09

LordSilvermort