Blazor FileUpload - Handle Files

FileUpload - Handle Files

Set up The FileUpload

Smart.FileUpload is a custom input element that allows uploading one or multiple files.

Add the FileUpload component to the Pages/Index.razor file. Set the UploadUrl property to the URL of the server-side upload handler:

@inject NavigationManager navigationManager;

<FileUpload Multiple DropZone="true" UploadUrl="@($"{navigationManager.BaseUri}api/fileupload")"></FileUpload>

Basic file upload

Create File Upload Controller

To handle the uploaded files, first create a "Controllers" folder. Inside create a new file called FileUploadController.cs

The FileUpload sends the selected files as part of a IFormCollection.
The following code creates a controller that will save the uploaded files in the "wwwroot/uploads" directory:

using Microsoft.AspNetCore.Mvc;

namespace MyBlazorApp.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class FileUploadController : ControllerBase
    {
        [HttpPost]
        public async Task<IActionResult> UploadFiles([FromForm] IFormCollection form)
        {
            if (form.Files.Count == 0)
            {
                return BadRequest("No files uploaded.");
            }

            var uploadsFolder = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot/uploads");

            // Ensure the uploads directory exists
            if (!Directory.Exists(uploadsFolder))
            {
                Directory.CreateDirectory(uploadsFolder);
            }

            foreach (var file in form.Files)
            {
                var filePath = Path.Combine(uploadsFolder, file.FileName);

                // Save the file
                using (var stream = new FileStream(filePath, FileMode.Create))
                {
                    await file.CopyToAsync(stream);
                }
            }

            return Ok($"{form.Files.Count} files uploaded successfully.");
        }
    }

} 

In order for the Controller to be called correctly, make sure the following services are registered in the Program.cs file:

builder.Services.AddControllers();
//.....
app.UseRouting();
app.MapControllers();

We can now see that the uploaded files are saved successfully in the wwwroot/uploads directoy of our App:

Basic file upload Saved files