Hello,

It's never has been so easy to upload a file using Blazor. Using this awesome package https://www.nuget.org/packages/Tewr.Blazor.FileReader/ makes the job.

Thanks https://www.creativejuiz.fr/blog/tutoriels/input-file-personnalise-css-js for the css!

Here's a gif of the final project:



Here's the final code, which is pretty straightforward


@page "/"
@using System.IO;
@inject IFileReaderService fileReaderService;
 
    <div class="js">
        <div class="input-file-container">
            <input id="my-file" type="file" @ref="@inputTypeFileElement" class="input-file" multiple @onchange="@ReadFile" />
            <label for="my-file" class="input-file-trigger" tabindex="0">Pick a file...</label>
        </div>
        <p class="file-return"></p>
    </div>
@if (progress.HasValue)
{
    @if (progress < 100)
    {
    <div class="progress">
        <div class="progress-bar" role="progressbar" style="width: @(progress)%;" aria-valuenow="@progress" aria-valuemin="0" aria-valuemax="100">@progress%</div>
    </div>
    }
    else
    {
        <h1>Upload succeeded!</h1>
    }
}
 
 
@functions {
    ElementRef inputTypeFileElement;
    public int? progress;
    public async Task ReadFile()
    {
        int countSize = 0;
        foreach (var file in await fileReaderService.CreateReference(inputTypeFileElement).EnumerateFilesAsync())
        {
            var fileInfo = await file.ReadFileInfoAsync();            
            using (var ms = new MemoryStream())
            {
                using (var fs = await file.OpenReadAsync())
                {
                    var bufferSize = 4096;
                    var buffer = new byte[bufferSize];
                    int count;
                    while ((count = await fs.ReadAsync(buffer0buffer.Length)) != 0)
                    {
                        ms.Write(buffer0count);
                        countSize += count;
                        progress = (int)(((decimal)countSize / fileInfo.Size) * 100);
                        this.StateHasChanged();
                    }
                    var fileName = Path.Combine(Directory.GetCurrentDirectory(), fileInfo.Name);
                    File.WriteAllBytes(fileNamems.ToArray());
                }
            }            
 
        }        
    }
}