Getting Started with Blazor File Upload in Blazor WASM App
29 Jun 202616 minutes to read
This section briefly explains about how to include Blazor File Upload component in a Blazor WebAssembly App using Visual Studio, Visual Studio Code, and the .NET CLI.
Create a new Blazor WebAssembly (Standalone) App
Create a Blazor WebAssembly App using Visual Studio via Microsoft Templates or the Blazor Extension.
Run the following command to create a new Blazor WebAssembly App.
dotnet new blazorwasm -o BlazorApp
cd BlazorAppAlternatively, create a Blazor WebAssembly App using Visual Studio Code via Microsoft Templates or the Blazor Extension, or the C# Dev Kit extension.
Run the following command to create a new Blazor WebAssembly App.
dotnet new blazorwasm -o BlazorApp
cd BlazorAppInstall the required Blazor packages
Install the Syncfusion.Blazor.Inputs and Syncfusion.Blazor.Themes NuGet packages. All Syncfusion Blazor packages are available on nuget.org. See the NuGet packages topic for details.
- Go to Tools → NuGet Package Manager → Manage NuGet Packages for Solution.
- Search the required NuGet packages (
Syncfusion.Blazor.InputsandSyncfusion.Blazor.Themes) and install them.
Alternatively, you can install the same packages using the Package Manager Console with the following commands.
Install-Package Syncfusion.Blazor.Inputs -Version 34.1.29
Install-Package Syncfusion.Blazor.Themes -Version 34.1.29Open the terminal and run the following commands.
dotnet add package Syncfusion.Blazor.Inputs -v 34.1.29
dotnet add package Syncfusion.Blazor.Themes -v 34.1.29Open the command prompt and run the following commands.
dotnet add package Syncfusion.Blazor.Inputs -v 34.1.29
dotnet add package Syncfusion.Blazor.Themes -v 34.1.29Add import namespaces
After the packages are installed, open the ~/_Imports.razor file and import the Syncfusion.Blazor and Syncfusion.Blazor.Inputs namespaces.
@using Syncfusion.Blazor
@using Syncfusion.Blazor.InputsRegister the Blazor service
Open the Program.cs file in Blazor WebAssembly App and register the Blazor service.
....
using Syncfusion.Blazor;
....
builder.Services.AddSyncfusionBlazor();
....Add stylesheet and script resources
The theme stylesheet and script can be accessed from NuGet through Static Web Assets. Include the stylesheet and script references in the ~wwwroot/index.html file.
...
<link href="_content/Syncfusion.Blazor.Themes/fluent2.css" rel="stylesheet" />
...
<script src="_content/Syncfusion.Blazor.Core/scripts/syncfusion-blazor.min.js" type="text/javascript"></script>Add Blazor File Upload component
Open a Razor file located in the ~/Pages/*.razor (for example, Home.razor) and add the Blazor File Upload component inside the razor file.
This component allows you to seamlessly integrate File Upload functionalities into your Blazor applications. It supports various features like asynchronous and synchronous uploads, file type validation, progress tracking, and custom templates. A common use case is enabling users to upload documents, images, or other files to a server, or process them directly within the client-side application.
Simple Code to render a Usable File Upload Component
The most basic way to render the File Upload component is by adding the <SfUploader> tag to your .razor page. By default, this component provides a clean interface for users to select files locally.
<SfUploader></SfUploader>Run the application
Press Ctrl+F5 (Windows) or ⌘+F5 (macOS) to launch the application. The Blazor File Upload component will render in your default web browser.
Open the terminal and run the following command.
dotnet runOpen the command prompt and run the following command.
dotnet runUse ValueChange Event
The ValueChange event fires when files are selected or removed from the uploader. This event is crucial for client-side processing of selected files, allowing you to access file details and their content, which is useful for previewing files or handling uploads without a server-side endpoint.
This example demonstrates how to use the ValueChange event to save uploaded files directly to a local directory when the AutoUpload property is set to true. This is useful for scenarios where you want to process files immediately after selection without an explicit upload button.
@using Syncfusion.Blazor.Inputs
@using System.IO
<SfUploader AutoUpload="true">
<UploaderEvents ValueChange="@OnChange"></UploaderEvents>
</SfUploader>
@code
{
private async Task OnChange(UploadChangeEventArgs args)
{
try
{
foreach (var fileEntry in args.Files)
{
// Define a path where you want to save the file.
var uploadsFolder = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot", "uploads");
if (!Directory.Exists(uploadsFolder))
{
Directory.CreateDirectory(uploadsFolder);
}
// Construct the full file path.
var filePath = Path.Combine(uploadsFolder, fileEntry.FileInfo.Name);
// Use a FileStream to write the uploaded file's content to the server.
await using (var fileStream = new FileStream(filePath, FileMode.Create, FileAccess.Write))
{
// OpenReadStream with long.MaxValue allows reading the entire stream.
await fileEntry.File.OpenReadStream(long.MaxValue).CopyToAsync(fileStream);
}
Console.WriteLine($"File '{fileEntry.FileInfo.Name}' saved successfully to '{filePath}'");
}
}
catch (Exception ex)
{
Console.WriteLine($"Error saving file: {ex.Message}");
}
}
}NOTE
When saving files directly in a Blazor Server application using
ValueChangeandAutoUpload, the files are saved on the server where the Blazor Server app is running, not on the client’s machine. You need appropriate file system permissions for the server process to write to the specified directory. Also, ensure the target directory (wwwroot/uploadsin this example) exists or is created programmatically. In a production environment, consider secure storage solutions for uploaded files.
Memory stream
When you need to process uploaded files in memory—perhaps for resizing images, reading content, or sending them to another service without saving them to disk first—using a MemoryStream is an efficient approach. This is particularly useful for temporary processing or when dealing with sensitive data that shouldn’t persist on the file system.
This example demonstrates how to read the content of an uploaded file into a MemoryStream Class`. This allows you to perform in-memory operations on the file, such as converting an image to a Base64 string, without requiring disk I/O.
@using Syncfusion.Blazor.Inputs
@using System.IO
<SfUploader AutoUpload="true">
<UploaderEvents ValueChange="@OnValueChangeMemoryStream"></UploaderEvents>
</SfUploader>
@if (!string.IsNullOrEmpty(base64Image))
{
<h4>Uploaded Image Preview (Base64)</h4>
<img src="@($"data:image/png;base64,{base64Image}")" style="max-width: 300px; height: auto;" />
}
@code
{
private string base64Image;
private async Task OnValueChangeMemoryStream(UploadChangeEventArgs args)
{
base64Image = string.Empty; // Clear previous image
foreach (var fileEntry in args.Files)
{
if (fileEntry.FileInfo.Type.StartsWith("image/", StringComparison.OrdinalIgnoreCase))
{
// Create a MemoryStream to hold the file content.
using var memoryStream = new MemoryStream();
// Copy the file's content from the upload stream to the MemoryStream.
await fileEntry.File.OpenReadStream(long.MaxValue).CopyToAsync(memoryStream);
// Convert the MemoryStream content to a byte array.
byte[] imageBytes = memoryStream.ToArray();
// Convert byte array to Base64 string for display or further processing.
base64Image = Convert.ToBase64String(imageBytes);
Console.WriteLine($"Image '{fileEntry.FileInfo.Name}' loaded into MemoryStream and converted to Base64.");
}
else
{
Console.WriteLine($"File '{fileEntry.FileInfo.Name}' is not an image and won't be processed for Base64 preview.");
// For non-image files, you could read their content as text or handle differently.
// Example for text file:
// memoryStream.Position = 0; // Reset stream position
// using var reader = new StreamReader(memoryStream);
// var content = await reader.ReadToEndAsync();
// Console.WriteLine($"Content of {fileEntry.FileInfo.Name}: {content}");
}
}
}
}NOTE
When using
MemoryStreamfor large files, be mindful of server memory consumption. If you expect very large files, consider processing them in chunks or saving them to temporary storage before processing to avoid out-of-memory exceptions. Thelong.MaxValueinOpenReadStreamindicates the maximum buffer size. In a Blazor Server app,Streamoperations occur on the server.
Created Event
The Created event fires after the File Upload component has been rendered and initialized. This event is a good place to perform any initial setup, attach custom event listeners to the component’s DOM elements, or apply custom styling that requires the component to be fully rendered.
This example shows how to use the Created event to add a custom message or dynamically change some aspect of the uploader’s appearance right after it’s created.
@using Syncfusion.Blazor.Inputs
<SfUploader>
<UploaderEvents Created="@OnUploaderCreated"></UploaderEvents>
</SfUploader>
<p>@statusMessage</p>
@code
{
private string statusMessage = "Uploader not yet created.";
private void OnUploaderCreated()
{
statusMessage = "File Uploader has been successfully created and initialized!";
Console.WriteLine(statusMessage);
// You could also interact with JavaScript to modify DOM here if needed.
// For example: JSRuntime.InvokeVoidAsync("someJsFunction");
}
}NOTE
The
Createdevent is useful for client-side JavaScript interop if you need to manipulate the DOM elements of the uploader component immediately after it’s ready. However, for most Blazor-specific customizations (like custom templates), you should use the built-in Blazor features.
File Selected Event
The FileSelected event is triggered when files are chosen from the file explorer dialog, but before the ValueChange event. This event provides an opportunity to perform validations on the selected files (e.g., file size, type, count) and decide whether to proceed with the upload/value change or cancel the selection. It’s ideal for immediate client-side feedback or preventative actions.
This example demonstrates how to use the FileSelected event to prevent files larger than a certain size.
@using Syncfusion.Blazor.Inputs
@using System.Linq
<SfUploader >
<UploaderEvents FileSelected="@OnFileSelected"></UploaderEvents>
</SfUploader>
<p>@validationMessage</p>
@code
{
private string validationMessage = "";
private readonly long MaxFileSize = 1024 * 1024; // 1 MB
private void OnFileSelected(SelectedEventArgs args)
{
validationMessage = "";
foreach (var file in args.FilesData)
{
if (file.Size > MaxFileSize)
{
validationMessage += $"Error: File '{file.Name}' exceeds {MaxFileSize / (1024 * 1024)} MB limit. ";
args.Cancel = true; // Prevents this file from being added
}
}
if (!string.IsNullOrEmpty(validationMessage))
{
Console.WriteLine(validationMessage);
}
else
{
Console.WriteLine("Files selected successfully and passed initial validation.");
}
}
}NOTE
Setting
args.Cancel = truein theFileSelectedevent will prevent the file (or files ifargs.Filescontains multiple) from being added to the uploader’s internal file list. This is a client-side validation and should be complemented with server-side validation for robust security and data integrity.
OnFileListRender
The OnFileListRender event allows you to customize individual file list items before they are rendered in the uploader’s UI. This is highly useful for scenarios where you need to display additional information alongside each file, such as a custom preview, metadata, or actions.
This example demonstrates how to use OnFileListRender
@using Syncfusion.Blazor.Inputs
<SfUploader @ref="fileobj" AutoUpload="false">
<UploaderEvents OnFileListRender="@OnFileListRenderHandler"></UploaderEvents>
<UploaderAsyncSettings SaveUrl="https://blazor.syncfusion.com/services/production/api/FileUploader/Save" RemoveUrl="https://blazor.syncfusion.com/services/production/api/FileUploader/Remove"></UploaderAsyncSettings>
</SfUploader>
@code
{
SfUploader fileobj;
private void OnFileListRenderHandler(FileListRenderingEventArgs args)
{
}
}NOTE
See also
- Getting Started with Blazor for Client-Side in .NET Core CLI
- Getting Started with Blazor for Server-side in Visual Studio
- Getting Started with Blazor for Server-Side in .NET Core CLI
- Getting Started with File Upload in Blazor WebAssembly using Visual Studio
- How to convert images to Base64 string with Blazor File Upload