blazor server upload file and save in csharp

To upload a file in Blazor server-side application, you can make use of the built-in InputFile component provided in the Microsoft.AspNetCore.Components.Forms namespace. The InputFile component contains a OnChange event that is triggered when the user selects a file in the file dialog window. This event can be handled to receive the selected file stream, which can then be saved to the server.

Here is an example code snippet that demonstrates how to upload a file and save it on the server:

main.cs
@page "/upload"
@using System.IO
@using Microsoft.AspNetCore.Hosting

<h1>Upload File</h1>

<div>
    <label for="fileInput">Select file:</label>
    <InputFile id="fileInput" OnChange="@HandleSelectedFile"/>
</div>

@code {
    private IWebHostEnvironment _environment;

    public Upload(IWebHostEnvironment environment)
    {
        _environment = environment;
    }

    private async Task HandleSelectedFile(InputFileChangeEventArgs e)
    {
        var file = e.File;
        var fileName = file.Name;

        // create a file stream
        var fileStream = file.OpenReadStream();

        // create a file path on the server to save the file
        string filePath = Path.Combine(_environment.WebRootPath, "uploads", fileName);

        // save the file
        using(var outputStream = new FileStream(filePath, FileMode.Create))
        {
            await fileStream.CopyToAsync(outputStream);
        }
    }
}
925 chars
38 lines

In the above example, the InputFile component is used to create a file input field on the UI. When a file is selected, the HandleSelectedFile method is called, which receives the selected file stream from the OnChange event. The file is then saved using the code block inside the method.

Note that in order to use the WebHostEnvironment service, you need to add it as a component service in the Startup.cs file of your application. You can add it to the ConfigureServices method as follows:

main.cs
public void ConfigureServices(IServiceCollection services)
{
    services.AddSingleton<IWebHostEnvironment>(env => HostingEnvironment);
    // ...
}
149 chars
6 lines

This will make the WebHostEnvironment service available for dependency injection in your Blazor components.

gistlibby LogSnag