Getting Started with Blazor File Upload Component

29 Jan 202410 minutes to read

This section briefly explains about how to include Blazor File Upload component in your Blazor Server App and Blazor WebAssembly App using Visual Studio.

Prerequisites

Create a new Blazor App in Visual Studio

You can create a Blazor Server App or Blazor WebAssembly App using Visual Studio via Microsoft Templates or the Syncfusion Blazor Extension.

Install Syncfusion Blazor Inputs and Themes NuGet in the App

To add Blazor File Upload component in the app, open the NuGet package manager in Visual Studio (Tools → NuGet Package Manager → Manage NuGet Packages for Solution), search and install Syncfusion.Blazor.Inputs and Syncfusion.Blazor.Themes. Alternatively, you can utilize the following package manager command to achieve the same.

Install-Package Syncfusion.Blazor.Inputs -Version 25.1.35
Install-Package Syncfusion.Blazor.Themes -Version 25.1.35

NOTE

Syncfusion Blazor components are available in nuget.org. Refer to NuGet packages topic for available NuGet packages list with component details.

Register Syncfusion Blazor Service

Open ~/_Imports.razor file and import the Syncfusion.Blazor and Syncfusion.Blazor.Inputs namespace.

@using Syncfusion.Blazor
@using Syncfusion.Blazor.Inputs

Now, register the Syncfusion Blazor Service in the ~/Program.cs file of your Blazor Server App or Blazor WebAssembly App.

using Microsoft.AspNetCore.Components;
using Microsoft.AspNetCore.Components.Web;
using Syncfusion.Blazor;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
builder.Services.AddRazorPages();
builder.Services.AddServerSideBlazor();
builder.Services.AddSyncfusionBlazor();

var app = builder.Build();
....
using Microsoft.AspNetCore.Components.Web;
using Microsoft.AspNetCore.Components.WebAssembly.Hosting;
using Syncfusion.Blazor;

var builder = WebAssemblyHostBuilder.CreateDefault(args);
builder.RootComponents.Add<App>("#app");
builder.RootComponents.Add<HeadOutlet>("head::after");

builder.Services.AddScoped(sp => new HttpClient { BaseAddress = new Uri(builder.HostEnvironment.BaseAddress) });

builder.Services.AddSyncfusionBlazor();
await builder.Build().RunAsync();
....

Add stylesheet and script resources

The theme stylesheet and script can be accessed from NuGet through Static Web Assets. Reference the stylesheet and script in the <head> of the main page as follows:

  • For .NET 6 Blazor Server app, include it in ~/Pages/_Layout.cshtml file.

  • For .NET 7 Blazor Server app, include it in the ~/Pages/_Host.cshtml file.

  • For Blazor WebAssembly app, include it in the ~/index.html file.

<head>
    ....
    <link href="_content/Syncfusion.Blazor.Themes/bootstrap5.css" rel="stylesheet" />
    <script src="_content/Syncfusion.Blazor.Core/scripts/syncfusion-blazor.min.js" type="text/javascript"></script>
</head>

NOTE

Check out the Blazor Themes topic to discover various methods (Static Web Assets, CDN, and CRG) for referencing themes in your Blazor application. Also, check out the Adding Script Reference topic to learn different approaches for adding script references in your Blazor application.

Add Blazor File Upload component

Add the Syncfusion Blazor File Upload component in the ~/Pages/Index.razor file.

<SfUploader></SfUploader>
  • Press Ctrl+F5 (Windows) or +F5 (macOS) to launch the application. This will render the Syncfusion Blazor File Upload component in your default web browser.
Blazor FileUpload Component

Without server-side API endpoint

You can upload the files and files of folders in the Blazor application without specifying the server-side API end point using AsyncSettings.

Save and Remove actions

You can get the uploaded files as file stream in the ValueChange event argument. Now, you can write the save handler inside ValueChange event to save the files to desired location. Find the save action code below.

@using Syncfusion.Blazor.Inputs
<SfUploader AutoUpload="true">
      <UploaderEvents ValueChange="@OnChange"></UploaderEvents>
</SfUploader>
@code {
    private async Task OnChange(UploadChangeEventArgs args)
    {
        try
        {
            foreach (var file in args.Files)
            {
                var path = @"" + file.FileInfo.Name;
                FileStream filestream = new FileStream(path, FileMode.Create, FileAccess.Write);
                await file.File.OpenReadStream(long.MaxValue).CopyToAsync(filestream);
                filestream.Close();
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.Message);
        }
    }
}

Blazor FileUpload displays Updated Files

While clicking on the remove icon in the file list, you will get the OnRemove event with removing file name as argument. So, you can write the remove handler inside OnRemove event to remove the particular file from desired location. Find the remove action code below.

Private void onRemove(RemovingEventArgs args)
{
    foreach(var removeFile in args.FilesData)
    {
        if (File.Exists(Path.Combine(@"rootPath", removeFile.Name)))
        {
            File.Delete(Path.Combine(@"rootPath", removeFile.Name))
        }
    }
}

With server-side API endpoint

The upload process requires save and remove action URL to manage the upload process in the server.

NOTE

  • The save action is necessary to handle the upload operation.

    * The remove action is optional, one can handle the removed files from server.

The save action handler upload the files that needs to be specified in the SaveUrl property.

The save handler receives the submitted files and manages the save process in server. After uploading the files to server location, the color of the selected file name changes to green and the remove icon is changed as bin icon.

The remove action is optional. The remove action handler removes the files that needs to be specified in the RemoveUrl property. OnActionComplete event triggers after all the selected files have been processed to upload successfully or failed to server.

[Route("api/[controller]")]

private IHostingEnvironment hostingEnv;

public SampleDataController(IHostingEnvironment env)
{
    this.hostingEnv = env;
}

[HttpPost("[action]")]
public void Save(IList<IFormFile> UploadFiles)
{
    try
    {
        foreach (var file in UploadFiles)
        {
            var filename = hostingEnv.ContentRootPath + $@"\{file.FileName}";
            if (!System.IO.File.Exists(filename))
            {
                using (FileStream fs = System.IO.File.Create(filename))
                {
                    file.CopyTo(fs);
                    fs.Flush();
                }
            }
        }
    }
    catch (Exception e)
    {
        Response.Clear();
        Response.StatusCode = 204;
        Response.HttpContext.Features.Get<IHttpResponseFeature>().ReasonPhrase = "File failed to upload";
        Response.HttpContext.Features.Get<IHttpResponseFeature>().ReasonPhrase = e.Message;
    }
}

[HttpPost("[action]")]
public void Remove(IList<IFormFile> UploadFiles)
{
    try
    {
        var filename = hostingEnv.ContentRootPath + $@"\{UploadFiles[0].FileName}";
        if (System.IO.File.Exists(filename))
        {
            System.IO.File.Delete(filename);
        }
    }
    catch (Exception e)
    {
        Response.Clear();
        Response.StatusCode = 200;
        Response.HttpContext.Features.Get<IHttpResponseFeature>().ReasonPhrase = "File removed successfully";
        Response.HttpContext.Features.Get<IHttpResponseFeature>().ReasonPhrase = e.Message;
    }
}

The OnFailure event is triggered when there is a failure in the AJAX request during the uploading or removing of files. It provides a way to handle and respond to any errors or issues that occur during the file upload or removal process.

<SfUploader ID="UploadFiles">
    <UploaderAsyncSettings SaveUrl="api/SampleData/Save" RemoveUrl="api/SampleData/Remove"></UploaderAsyncSettings>
    <UploaderEvents OnFailure="@OnFailureHandler" OnActionComplete="@OnActionCompleteHandler"></UploaderEvents>
</SfUploader>
@code {
    private void OnFailureHandler(FailureEventArgs args)
    {
        // Here, you can customize your code.
    }
    private void OnActionCompleteHandler(ActionCompleteEventArgs args)
    {
        // Here, you can customize your code.
    }
}

Configure allowed file types

You can allow the specific files alone to upload using the AllowedExtensions property. The extension can be represented as collection by comma separators. The uploader component filters the selected or dropped files to match against the specified file types and processes the upload operation. The validation happens when you specify value to inline attribute to accept the original input element.

<SfUploader AllowedExtensions=".doc, docx, .xls, xlsx"></SfUploader>
Allowing Specific Files in Blazor FileUpload

NOTE

View Sample in GitHub.

See also