0

I want to be able to upload multiple files via FileInput but got stuck when it comes to parallelism. I simply want to show the user a progress-bar (depending on overall read bytes) and afterwards a simple list of what has already been processed.

Currently my callback is looking like this:

private async Task HandleInputFileChange(InputFileChangeEventArgs fileChangeEventArgs)
{
    _filesProcessed.Clear();

    _alreadyRead = 0;

    var browserFiles = fileChangeEventArgs.GetMultipleFiles();

    _max = browserFiles.Sum(bf => bf.Size);

    await Task.WhenAll(browserFiles.Select(browserFile => Task.Run(async () =>
    {
        var trustedFileName = Path.GetRandomFileName();
        var filePath = Path.Combine(HostEnvironment.ContentRootPath, HostEnvironment.EnvironmentName, FolderName, trustedFileName);

        await using var fileStream = new FileStream(filePath, FileMode.Create);
        await using var readStream = browserFile.OpenReadStream(AllowedFileSize);

        int bytesRead;

        var readBuffer = new byte[1024 * 10];

        while ((bytesRead = await readStream.ReadAsync(readBuffer)) != 0)
        {
            _alreadyRead += bytesRead;

            await fileStream.WriteAsync(readBuffer, 0, bytesRead);

            await InvokeAsync(StateHasChanged);
        }

        _filesProcessed.Add(browserFile);
    })));
} 

However, with this code I mostly end up in a NullReferenceException at

Microsoft.AspNetCore.Components.Server.Circuits.RemoteJSDataStream.ReceiveData(RemoteJSRuntime runtime, Int64 streamId, Int64 chunkId, Byte[] chunk, String error)

Currently I'm not even sure if this is possible to do or not as it may seem to be an issue with how things get synchronized by the framework.

KingKerosin
  • 3,639
  • 4
  • 38
  • 77
  • `Select(browserFile => Task.Run(async () =>` <-- Why are you doing this? ([It won't work](https://stackoverflow.com/questions/70118465/in-blazor-what-is-the-difference-between-await-task-runstatehaschanged-and)) – Dai Oct 07 '22 at 17:56
  • @Dai Because to have each file processed in its own task. What would be the workaround instead of having this and using `Task.WhenAll`? – KingKerosin Oct 07 '22 at 18:17
  • Nevermind, I thought you were using client-side Blazor. – Dai Oct 07 '22 at 18:19

0 Answers0