File Upload in Blazor Server ASP.NET Core 5.0

File Upload in Blazor Server

This blog going to explain how to upload the file in Blazor server. The InputFile file component helps to upload the file in Blazor.

The following is a razor page code. Here, the InputFile component is added to read the browser file into .NET code. It will render the <input type="file" > HTML element. In the code the InputFile component will call the UploadFile method on the change event. The InputFileChangeEventArgs help to access the file. In the UploadFile method the FileStream will create a file on specific path.

Index.razor
@page "/"
@using System.IO
@using Microsoft.AspNetCore.Hosting
@inject IWebHostEnvironment Environment

<InputFile OnChange="@UploadFile" />

@if (ImgUrl != null)
{
    <div>
        <img src="@ImgUrl" style="width:100px" />
    </div>
}

@code{
    private string ImgUrl;

    private async Task UploadFile(InputFileChangeEventArgs e)
    {
        var path = Path.Combine(Environment.ContentRootPath, "wwwroot", "upload", e.File.Name);

        await using FileStream fs = new(path, FileMode.Create);
        await e.File.OpenReadStream().CopyToAsync(fs);
        ImgUrl = Path.Combine("https://localhost:44355/", "upload", e.File.Name);
    }
}

Note:
To upload a multiple file, add multiple attribute.

<InputFile OnChange="@UploadFile" multiple />

The following is an output of the above code.

File Upload in Blazor Server ASP.NET Core 5.0

I hope this helps you. Keep coding.

Comments

Popular posts from this blog

Entity Framework Core (EF) with SQL Server LocalDB

SignalR with JavaScript in ASP.NET Core MVC

Localization in ASP.NET Core MVC with Example