How can I help you?
Getting Started with Blazor File Upload Component in Web App
14 Apr 202617 minutes to read
This section briefly explains about how to include the Syncfusion® Blazor File Upload component in your Blazor Web App using Visual Studio, Visual Studio Code, and the .NET CLI.
Prerequisites
Create a new Blazor Web App in Visual Studio
Create a Blazor Web App using Visual Studio via Microsoft Templates or the Syncfusion® Blazor Extension. For detailed instructions, refer to the Blazor Web App Getting Started documentation.
Prerequisites
Create a new Blazor Web App in Visual Studio Code
Create a Blazor Web App using Visual Studio Code via Microsoft Templates or the Syncfusion® Blazor Extension. For detailed instructions, refer to the Blazor Web App Getting Started documentation.
For example, in a Blazor Web App with the Auto interactive render mode, use the following commands in the integrated terminal (Ctrl+`):
dotnet new blazor -o BlazorWebApp -int Auto
cd BlazorWebApp
cd BlazorWebApp.ClientPrerequisites
Install the latest version of .NET SDK. If you previously installed the SDK, determine the installed version by executing the following command in a command prompt (Windows) or terminal (macOS/Linux).
dotnet --versionCreate a Blazor Web App using .NET CLI
Run the following command to create a new Blazor Web App in a command prompt (Windows) or terminal (macOS) or command shell (Linux). For detailed instructions, refer to the Blazor Web App Getting Started documentation.
For example, in a Blazor Web App with the Auto interactive render mode, use the following commands:
dotnet new blazor -o BlazorWebApp -int Auto
cd BlazorWebApp
cd BlazorWebApp.ClientNOTE
Configure the appropriate Interactive render mode and Interactivity location while creating a Blazor Web App. For detailed information, refer to the interactive render mode documentation.
Install Syncfusion® Blazor packages
Install Syncfusion.Blazor.Inputs and Syncfusion.Blazor.Themes NuGet packages in your project using the NuGet Package Manager in Visual Studio (Tools → NuGet Package Manager → Manage NuGet Packages for Solution), or the integrated terminal in Visual Studio Code (dotnet add package), or the .NET CLI.
Alternatively, run the following commands in the Package Manager Console to achieve the same.
Install-Package Syncfusion.Blazor.Inputs -Version 33.1.44
Install-Package Syncfusion.Blazor.Themes -Version 33.1.44NOTE
All Syncfusion Blazor packages are available on nuget.org. If using the
WebAssemblyorAutorender modes, install these packages in the client project.
Add import namespaces
After the packages are installed, open the ~/_Imports.razor file in the client project and import the Syncfusion.Blazor and Syncfusion.Blazor.Inputs namespaces.
@using Syncfusion.Blazor
@using Syncfusion.Blazor.InputsRegister Syncfusion® Blazor service
Register the Syncfusion® Blazor service in the Program.cs file of your Blazor Web App.
....
using Syncfusion.Blazor;
....
builder.Services.AddSyncfusionBlazor();
....NOTE
If the Interactive Render Mode is set to
WebAssemblyorAuto, register the Syncfusion® Blazor service in Program.cs files of both the server and client projects in your Blazor Web App.
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 ~/Components/App.razor 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>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 Syncfusion® Blazor File Upload component
Add the Syncfusion® Blazor File Upload component in the ~/Components/Pages/*.razor file. If the interactivity location is set to Per page/component in the Web App, define a render mode at the top of the ~Pages/*.razor file. (For example, InteractiveServer, InteractiveWebAssembly or InteractiveAuto).
NOTE
If the Interactivity Location is set to
GlobalwithAutoorWebAssembly, the render mode is automatically configured in theApp.razorfile by default.
@* desired render mode define here *@
@rendermode InteractiveAuto<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.
Use 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.
// For a Blazor Server app, this path will be on the server.
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 = "Syncfusion 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 Syncfusion® Blazor for client-side in .NET Core CLI
- Getting Started with Syncfusion® Blazor for client-side in Visual Studio
- Getting Started with Syncfusion® Blazor for server-side in .NET Core CLI
- Getting Started with Syncfusion® File Upload in Blazor WebAssembly using Visual Studio
- How to convert images to Base64 string with Blazor File Upload