diff --git a/blazor/file-upload/getting-started-with-maui-app.md b/blazor/file-upload/getting-started-with-maui-app.md
index 6662b07e35..789abeef57 100644
--- a/blazor/file-upload/getting-started-with-maui-app.md
+++ b/blazor/file-upload/getting-started-with-maui-app.md
@@ -3,13 +3,13 @@ layout: post
title: Getting Started with FileUpload in Blazor MAUI App | Syncfusion
description: Checkout and learn about the documentation for getting started with Blazor FileUpload Component in Blazor MAUI App.
platform: Blazor
-control: File Upload
+control: FileUpload
documentation: ug
---
# Getting Started with Blazor File Upload Component
-This guide describes how to integrate the Syncfusion® Blazor File Upload component into a .NET MAUI Blazor application. It covers setup using Visual Studio and Visual Studio Code, adding required packages, registering resources, and rendering the component.
+This section guides you through the step-by-step process of integrating the Syncfusion® Blazor File Upload component into your Blazor MAUI application using both Visual Studio and Visual Studio Code.
{% tabcontents %}
@@ -17,21 +17,15 @@ This guide describes how to integrate the Syncfusion&
## Prerequisites
-To use .NET MAUI project templates, install the Mobile development with .NET workload for Visual Studio. For details, refer to the .NET MAUI installation instructions or the Syncfusion Blazor extension documentation.
-
-- .NET MAUI installation: https://learn.microsoft.com/en-us/dotnet/MAUI/get-started/installation?tabs=vswin
-- Syncfusion Blazor Extension: https://blazor.syncfusion.com/documentation/visual-studio-integration/template-studio
+To use the MAUI project templates, install the Mobile development with the .NET extension for Visual Studio. For more details, refer to [here](https://learn.microsoft.com/en-us/dotnet/MAUI/get-started/installation?tabs=vswin) or the [Syncfusion® Blazor Extension](https://blazor.syncfusion.com/documentation/visual-studio-integration/template-studio).
## Create a new Blazor MAUI App in Visual Studio
-Create a Blazor MAUI App using Visual Studio via [Microsoft Templates](https://learn.microsoft.com/en-us/dotnet/maui/get-started/first-app?pivots=devices-windows&view=net-maui-9.0&tabs=vswin). For detailed instructions, refer to [this Blazor MAUI App Getting Started](https://blazor.syncfusion.com/documentation/getting-started/maui-blazor-app) documentation.
+You can create a Blazor MAUI App using Visual Studio via [Microsoft Templates](https://learn.microsoft.com/en-us/dotnet/maui/get-started/first-app?pivots=devices-windows&view=net-maui-9.0&tabs=vswin). For detailed instructions, refer to [this Blazor MAUI App Getting Started](https://blazor.syncfusion.com/documentation/getting-started/maui-blazor-app) documentation.
## Install Syncfusion® Blazor Inputs and Themes NuGet in the app
-To use the Blazor File Upload component, install the following packages via the NuGet Package Manager (Tools → NuGet Package Manager → Manage NuGet Packages for Solution):
-
-- Syncfusion.Blazor.Inputs
-- Syncfusion.Blazor.Themes
+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](https://www.nuget.org/packages/Syncfusion.Blazor.Inputs) and [Syncfusion.Blazor.Themes](https://www.nuget.org/packages/Syncfusion.Blazor.Themes/).
{% tabs %}
{% highlight C# tabtitle="Package Manager" %}
@@ -50,18 +44,15 @@ N> Syncfusion® Blazor components are availa
## Prerequisites
-Ensure the .NET MAUI workload is installed. Visual Studio Code uses the .NET CLI to create and manage projects. For details, see the .NET MAUI installation guide and the Syncfusion Blazor extension documentation for VS Code.
-
-- .NET MAUI installation: https://learn.microsoft.com/en-us/dotnet/maui/get-started/installation?view=net-maui-9.0&tabs=visual-studio-code
-- Syncfusion Blazor Extension (VS Code): https://blazor.syncfusion.com/documentation/visual-studio-code-integration/create-project
+To use the MAUI project templates, install the Mobile development with the .NET extension for Visual Studio Code. For more details, refer to [here](https://learn.microsoft.com/en-us/dotnet/maui/get-started/installation?view=net-maui-9.0&tabs=visual-studio-code) or the [Syncfusion® Blazor Extension](https://blazor.syncfusion.com/documentation/visual-studio-code-integration/create-project).
## Create a new Blazor MAUI App in Visual Studio Code
-Create a Blazor MAUI App using Visual Studio Code via [Microsoft templates](https://learn.microsoft.com/en-us/dotnet/maui/get-started/first-app?pivots=devices-windows&view=net-maui-9.0&tabs=visual-studio-code) or the [Syncfusion® Blazor Extension](https://blazor.syncfusion.com/documentation/visual-studio-code-integration/create-project). For detailed instructions, refer to [this Blazor MAUI App Getting Started](https://blazor.syncfusion.com/documentation/getting-started/maui-blazor-app) documentation.
+You can create a Blazor MAUI App using Visual Studio Code via [Microsoft Templates](https://learn.microsoft.com/en-us/dotnet/maui/get-started/first-app?pivots=devices-windows&view=net-maui-9.0&tabs=visual-studio-code) or the [Syncfusion® Blazor Extension](https://blazor.syncfusion.com/documentation/visual-studio-code-integration/create-project). For detailed instructions, refer to [this Blazor MAUI App Getting Started](https://blazor.syncfusion.com/documentation/getting-started/maui-blazor-app) documentation.
-## Install Blazor Inputs and Themes NuGet in the App
+## 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](https://www.nuget.org/packages/Syncfusion.Blazor.Inputs) and [Syncfusion.Blazor.Themes](https://www.nuget.org/packages/Syncfusion.Blazor.Themes/).
+To add **Blazor File Upload** component in the app, install [Syncfusion.Blazor.Inputs](https://www.nuget.org/packages/Syncfusion.Blazor.Inputs) and [Syncfusion.Blazor.Themes](https://www.nuget.org/packages/Syncfusion.Blazor.Themes/) using the .NET CLI.
{% tabs %}
@@ -83,12 +74,12 @@ N> Syncfusion® Blazor components are availa
## Add Import Namespaces
-Open **~/_Imports.razor** and import the `Syncfusion.Blazor` and `Syncfusion.Blazor.Inputs` namespaces.
+Open the **~/_Imports.razor** file and import the `Syncfusion.Blazor` and `Syncfusion.Blazor.Inputs` namespace.
{% tabs %}
{% highlight razor tabtitle="~/_Imports.razor" %}
-@using Syncfusion.Blazor
+@using Syncfusion.Blazor
@using Syncfusion.Blazor.Inputs
{% endhighlight %}
@@ -134,7 +125,7 @@ namespace MauiBlazorWindow;
## Add stylesheet and script resources
-The theme stylesheet and scripts are provided via Static Web Assets from NuGet. Add the references to the head section of ~/wwwroot/index.html in the MAUI project.
+The theme stylesheet and script can be accessed from NuGet through [Static Web Assets](https://blazor.syncfusion.com/documentation/appearance/themes#static-web-assets). Include the stylesheet and script references in the `` section of the **~/index.html** file.
```html
@@ -142,16 +133,22 @@ The theme stylesheet and scripts are provided via Static Web Assets from NuGet.
- //Blazor File Upload Component script reference.
+
```
N> Check out the [Blazor Themes](https://blazor.syncfusion.com/documentation/appearance/themes) topic to discover various methods ([Static Web Assets](https://blazor.syncfusion.com/documentation/appearance/themes#static-web-assets), [CDN](https://blazor.syncfusion.com/documentation/appearance/themes#cdn-reference), and [CRG](https://blazor.syncfusion.com/documentation/common/custom-resource-generator)) for referencing themes in your Blazor application. Also, check out the [Adding Script Reference](https://blazor.syncfusion.com/documentation/common/adding-script-references) topic to learn different approaches for adding script references in your Blazor application.
-## Add Blazor File Upload component
+## Add Syncfusion® Blazor File Upload component
+
+The Syncfusion Blazor File Upload 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
Add the Syncfusion® Blazor File Upload component in the **~/Pages/Index.razor** file.
+The most basic way to render the File Upload component is by adding the `` tag to your `.razor` page. By default, this component provides a clean interface for users to select files locally.
+
{% tabs %}
{% highlight razor %}
@@ -162,51 +159,77 @@ Add the Syncfusion® Blazor File Upload comp
### How to Run the Sample on Windows
-Run the sample in Windows Machine mode to host the .NET MAUI Blazor app on Windows.
+Run the sample in Windows Machine mode, and it will run Blazor MAUI in Windows.

### How to Run the Sample on Android
-To run the Blazor File Upload component in an Android .NET MAUI app using the Android emulator, follow these steps:
+To run the Blazor DataGrid in a Blazor Android MAUI application using the Android emulator, follow these steps:
-- Install and launch the Android emulator: https://learn.microsoft.com/en-us/dotnet/maui/android/emulator/device-manager#android-device-manager-on-windows
+Refer [here](https://learn.microsoft.com/en-us/dotnet/maui/android/emulator/device-manager#android-device-manager-on-windows) to install and launch Android emulator.
-N> If issues occur with the Android Emulator, see Troubleshooting Android Emulator for guidance: https://learn.microsoft.com/en-us/dotnet/maui/android/emulator/troubleshooting.
+N> If you encounter any errors while using the Android Emulator, refer to the following link for troubleshooting guidance[Troubleshooting Android Emulator](https://learn.microsoft.com/en-us/dotnet/maui/android/emulator/troubleshooting).
-
-## Without server-side API endpoint
+* 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.
-Upload the files and files of folders in the Blazor application without specifying the server-side API end point using [AsyncSettings](https://help.syncfusion.com/cr/blazor/Syncfusion.Blazor.Inputs.UploaderAsyncSettings.html).
+{% previewsample "https://blazorplayground.syncfusion.com/embed/LXBJXsrOqbMEOurR?appbar=false&editor=false&result=true&errorlist=false&theme=bootstrap5" backgroundimage "[Blazor FileUpload Component](./images/blazor-fileupload-component.png)" %}
-### Save and Remove actions
+* 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.
-Get the uploaded files as file stream in the [ValueChange](https://help.syncfusion.com/cr/blazor/Syncfusion.Blazor.Inputs.UploaderEvents.html#Syncfusion_Blazor_Inputs_UploaderEvents_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.
+{% previewsample "https://blazorplayground.syncfusion.com/embed/LXBJXsrOqbMEOurR?appbar=false&editor=false&result=true&errorlist=false&theme=bootstrap5" backgroundimage "[Blazor FileUpload Component](./images/blazor-fileupload-component.png)" %}
+
+
+
+## Use ValueChange Event
+
+The [`ValueChange`](https://help.syncfusion.com/cr/blazor/Syncfusion.Blazor.Inputs.UploaderEvents.html#Syncfusion_Blazor_Inputs_UploaderEvents_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.
+
+### Code Example
+
+This example demonstrates how to use the [`ValueChange`](https://help.syncfusion.com/cr/blazor/Syncfusion.Blazor.Inputs.UploaderEvents.html#Syncfusion_Blazor_Inputs_UploaderEvents_ValueChange) event to save uploaded files directly to a local directory when the [`AutoUpload`](https://help.syncfusion.com/cr/blazor/Syncfusion.Blazor.Inputs.SfUploader.html#Syncfusion_Blazor_Inputs_SfUploader_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.
{% tabs %}
{% highlight razor %}
@using Syncfusion.Blazor.Inputs
+@using System.IO
+
+
@code {
private async Task OnChange(UploadChangeEventArgs args)
{
try
{
- foreach (var file in args.Files)
+ foreach (var fileEntry 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();
+ // 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(ex.Message);
+ Console.WriteLine($"Error saving file: {ex.Message}");
}
}
}
@@ -214,20 +237,71 @@ Get the uploaded files as file stream in the [ValueChange](https://help.syncfusi
{% endhighlight %}
{% endtabs %}
-
+N> When saving files directly in a Blazor Server application using [`ValueChange`](https://help.syncfusion.com/cr/blazor/Syncfusion.Blazor.Inputs.UploaderEvents.html#Syncfusion_Blazor_Inputs_UploaderEvents_ValueChange) and [`AutoUpload`](https://help.syncfusion.com/cr/blazor/Syncfusion.Blazor.Inputs.SfUploader.html#Syncfusion_Blazor_Inputs_SfUploader_AutoUpload), 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/uploads` in this example) exists or is created programmatically. In a production environment, consider secure storage solutions for uploaded files.
+
+{% previewsample "https://blazorplayground.syncfusion.com/embed/hDVyZkrqBvaSlvht?appbar=false&editor=false&result=true&errorlist=false&theme=bootstrap5" %}
-While clicking on the remove icon in the file list, you will get the [OnRemove](https://help.syncfusion.com/cr/blazor/Syncfusion.Blazor.Inputs.UploaderEvents.html#Syncfusion_Blazor_Inputs_UploaderEvents_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.
+
+
+
+## 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.
+
+### Code Example
+
+This example demonstrates how to read the content of an uploaded file into a [MemoryStream Class](https://learn.microsoft.com/en-us/dotnet/api/system.io.memorystream)`. 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.
{% tabs %}
-{% highlight cshtml %}
+{% highlight razor %}
-Private void onRemove(RemovingEventArgs args)
+@using Syncfusion.Blazor.Inputs
+@using System.IO
+
+
+
+
+
+@if (!string.IsNullOrEmpty(base64Image))
{
- foreach(var removeFile in args.FilesData)
+
Uploaded Image Preview (Base64)
+
+}
+
+@code {
+ private string base64Image;
+
+ private async Task OnValueChangeMemoryStream(UploadChangeEventArgs args)
{
- if (File.Exists(Path.Combine(@"rootPath", removeFile.Name)))
+ base64Image = string.Empty; // Clear previous image
+
+ foreach (var fileEntry in args.Files)
{
- File.Delete(Path.Combine(@"rootPath", removeFile.Name))
+ 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}");
+ }
}
}
}
@@ -235,114 +309,144 @@ Private void onRemove(RemovingEventArgs args)
{% endhighlight %}
{% endtabs %}
-## With server-side API endpoint
+N> When using `MemoryStream` for 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. The `long.MaxValue` in `OpenReadStream` indicates the maximum buffer size. In a Blazor Server app, `Stream` operations occur on the server.
+
+{% previewsample "https://blazorplayground.syncfusion.com/embed/BjreNaLUhdwxzvHS?appbar=false&editor=false&result=true&errorlist=false&theme=bootstrap5" %}
-The upload process can also be integrated with server endpoints via SaveUrl and RemoveUrl to manage files on the server.
+
-N> * The save action is required to handle file uploads on the server.
- * The remove action is optional and handles deleting files on the server.
-The save action handler upload the files that needs to be specified in the [SaveUrl](https://help.syncfusion.com/cr/blazor/Syncfusion.Blazor.Inputs.UploaderAsyncSettings.html#Syncfusion_Blazor_Inputs_UploaderAsyncSettings_SaveUrl) property.
+## Created Event
-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 [`Created`](https://help.syncfusion.com/cr/blazor/Syncfusion.Blazor.Inputs.UploaderEvents.html#Syncfusion_Blazor_Inputs_UploaderEvents_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.
-The remove action is optional. The remove action handler removes the files that needs to be specified in the [RemoveUrl](https://help.syncfusion.com/cr/blazor/Syncfusion.Blazor.Inputs.UploaderAsyncSettings.html#Syncfusion_Blazor_Inputs_UploaderAsyncSettings_RemoveUrl) property. [OnActionComplete](https://help.syncfusion.com/cr/blazor/Syncfusion.Blazor.Inputs.UploaderEvents.html#Syncfusion_Blazor_Inputs_UploaderEvents_OnActionComplete) event triggers after all the selected files have been processed to upload successfully or failed to server.
+### Code Example
+
+This example shows how to use the [`Created`](https://help.syncfusion.com/cr/blazor/Syncfusion.Blazor.Inputs.UploaderEvents.html#Syncfusion_Blazor_Inputs_UploaderEvents_Created) event to add a custom message or dynamically change some aspect of the uploader's appearance right after it's created.
{% tabs %}
-{% highlight cshtml %}
+{% highlight razor %}
-[Route("api/[controller]")]
-public class SampleDataController : Controller
-{
- public string uploads = ".\\Uploaded Files"; // replace with your directory path
+@using Syncfusion.Blazor.Inputs
- [HttpPost("[action]")]
- public async Task Save(IFormFile UploadFiles) // Save the uploaded file here
- {
- if (UploadFiles.Length > 0)
- {
- //Create directory if not exists
- if (!Directory.Exists(uploads))
- {
- Directory.CreateDirectory(uploads);
- }
+
+
+
- var filePath = Path.Combine(uploads, UploadFiles.FileName);
- if (System.IO.File.Exists(filePath))
- {
- //Return conflict status code
- return new StatusCodeResult(StatusCodes.Status409Conflict);
- }
- using (var fileStream = new FileStream(filePath, FileMode.Create))
- {
- //Save the uploaded file to server
- await UploadFiles.CopyToAsync(fileStream);
- }
- }
- return Ok();
- }
+
@statusMessage
+@code {
+ private string statusMessage = "Uploader not yet created.";
- [HttpPost("[action]")]
- public void Remove(string UploadFiles) // Delete the uploaded file here
+ private void OnUploaderCreated()
{
- if(UploadFiles != null)
- {
- var filePath = Path.Combine(uploads, UploadFiles);
- if (System.IO.File.Exists(filePath))
- {
- //Delete the file from server
- System.IO.File.Delete(filePath);
- }
- }
+ 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");
}
}
{% endhighlight %}
{% endtabs %}
-The [OnFailure](https://help.syncfusion.com/cr/blazor/Syncfusion.Blazor.Inputs.UploaderEvents.html#Syncfusion_Blazor_Inputs_UploaderEvents_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.
+N> The [`Created`](https://help.syncfusion.com/cr/blazor/Syncfusion.Blazor.Inputs.UploaderEvents.html#Syncfusion_Blazor_Inputs_UploaderEvents_Created) event 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.
+
+{% previewsample "https://blazorplayground.syncfusion.com/embed/VtLyNuVUBGtPZrdo?appbar=false&editor=false&result=true&errorlist=false&theme=bootstrap5" %}
+
+
+
+
+## File Selected Event
+
+The [`FileSelected Event`](https://help.syncfusion.com/cr/blazor/Syncfusion.Blazor.Inputs.UploaderEvents.html#Syncfusion_Blazor_Inputs_UploaderEvents_FileSelected)event is triggered when files are chosen from the file explorer dialog, but **before** the [`ValueChange`](https://help.syncfusion.com/cr/blazor/Syncfusion.Blazor.Inputs.UploaderEvents.html#Syncfusion_Blazor_Inputs_UploaderEvents_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.
+
+### Code Example
+
+This example demonstrates how to use the [FileSelected Event](https://help.syncfusion.com/cr/blazor/Syncfusion.Blazor.Inputs.UploaderEvents.html#Syncfusion_Blazor_Inputs_UploaderEvents_FileSelected) event to prevent files larger than a certain size.
{% tabs %}
{% highlight razor %}
-
-
-
+@using Syncfusion.Blazor.Inputs
+@using System.Linq
+
+
+
+
@validationMessage
+
@code {
- private void OnFailureHandler(FailureEventArgs args)
- {
- // Here, you can customize your code.
- }
- private void OnActionCompleteHandler(ActionCompleteEventArgs args)
+ private string validationMessage = "";
+ private readonly long MaxFileSize = 1024 * 1024; // 1 MB
+
+ private void OnFileSelected(SelectedEventArgs args)
{
- // Here, you can customize your code.
+ 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.");
+ }
}
}
{% endhighlight %}
{% endtabs %}
-## Configure allowed file types
+N> Setting `args.Cancel = true` in the `FileSelected` event will prevent the file (or files if `args.Files` contains 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.
+
+{% previewsample "https://blazorplayground.syncfusion.com/embed/BDLIZuBUVwEJoJpz?appbar=false&editor=false&result=true&errorlist=false&theme=bootstrap5" %}
+
+
+
+
+## OnFileListRender
-Allow the specific files alone to upload using the [AllowedExtensions](https://help.syncfusion.com/cr/blazor/Syncfusion.Blazor.Inputs.UploaderModel.html#Syncfusion_Blazor_Inputs_UploaderModel_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.
+The [`OnFileListRender`](https://help.syncfusion.com/cr/blazor/Syncfusion.Blazor.Inputs.UploaderEvents.html#Syncfusion_Blazor_Inputs_UploaderEvents_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.
+
+### Code Example
+
+This example demonstrates how to use [`OnFileListRender`](https://help.syncfusion.com/cr/blazor/Syncfusion.Blazor.Inputs.UploaderEvents.html#Syncfusion_Blazor_Inputs_UploaderEvents_OnFileListRender)
{% tabs %}
{% highlight razor %}
-
+@using Syncfusion.Blazor.Inputs
+
+
+
+
+
+
+@code {
+ SfUploader fileobj;
+ private void OnFileListRenderHandler(FileListRenderingEventArgs args)
+ {
+
+ }
+}
{% endhighlight %}
{% endtabs %}
-{% previewsample "https://blazorplayground.syncfusion.com/embed/rXhzDsrOqbKVNviI?appbar=false&editor=false&result=true&errorlist=false&theme=bootstrap5" backgroundimage "[Allowing Specific Files in Blazor FileUpload](./images/blazor-fileupload-allow-specific-file.png)" %}
-
-N> View the sample on GitHub for a complete getting-started example: https://github.com/SyncfusionExamples/Blazor-Getting-Started-Examples/tree/main/FileUpload.
+N> [View Sample in GitHub](https://github.com/SyncfusionExamples/Blazor-Getting-Started-Examples/tree/main/FileUpload).
## See also
-1. [Getting started with Syncfusion® Blazor for client-side in .NET Core CLI](https://blazor.syncfusion.com/documentation/getting-started/blazor-webassembly-dotnet-cli)
-2. [Getting started with Syncfusion® Blazor for client-side in Visual Studio](https://blazor.syncfusion.com/documentation/getting-started/blazor-webassembly-visual-studio)
-3. [Getting started with Syncfusion® Blazor for server-side in .NET Core CLI](https://blazor.syncfusion.com/documentation/getting-started/blazor-server-side-dotnet-cli)
-4. [Getting started with Syncfusion® File Upload in Blazor WebAssembly using Visual Studio](https://blazor.syncfusion.com/documentation/file-upload/how-to/getting-started-with-blazor-webassembly)
\ No newline at end of file
+1. [Getting Started with Syncfusion® Blazor for client-side in .NET Core CLI](https://blazor.syncfusion.com/documentation/getting-started/blazor-webassembly-dotnet-cli)
+2. [Getting Started with Syncfusion® Blazor for client-side in Visual Studio](https://blazor.syncfusion.com/documentation/getting-started/blazor-webassembly-visual-studio)
+3. [Getting Started with Syncfusion® Blazor for server-side in .NET Core CLI](https://blazor.syncfusion.com/documentation/getting-started/blazor-server-side-dotnet-cli)
+4. [Getting Started with Syncfusion® File Upload in Blazor WebAssembly using Visual Studio](https://blazor.syncfusion.com/documentation/file-upload/how-to/getting-started-with-blazor-webassembly)
+5. [How to convert images to Base64 string with Blazor File Upload](https://support.syncfusion.com/kb/article/21178/how-to-convert-images-to-base64-string-with-blazor-file-upload)
\ No newline at end of file
diff --git a/blazor/file-upload/getting-started-with-server-app.md b/blazor/file-upload/getting-started-with-server-app.md
index cc2988b435..77619e06ce 100644
--- a/blazor/file-upload/getting-started-with-server-app.md
+++ b/blazor/file-upload/getting-started-with-server-app.md
@@ -3,15 +3,15 @@ layout: post
title: Getting Started with Blazor FileUpload Component | Syncfusion
description: Checkout and learn about getting started with Blazor FileUpload component in Blazor Server Application.
platform: Blazor
-control: File Upload
+control: FileUpload
documentation: ug
---
-# Getting Started with Blazor File Upload Component in Server App
+# Getting Started with Blazor File Upload Component
-This section explains how to add the [Blazor File Upload](https://www.syncfusion.com/blazor-components/blazor-file-upload) component to a Blazor Server app using Visual Studio, Visual Studio Code, or the .NET CLI.
+This section briefly explains how to include the [Blazor File Upload](https://www.syncfusion.com/blazor-components/blazor-tree-grid) component in your Blazor Server Application using Visual Studio, Visual Studio Code, and the .NET CLI.
-To get started quickly with the Blazor File Upload component, review the sample in this [GitHub repository](https://github.com/SyncfusionExamples/Blazor-Getting-Started-Examples/tree/main/FileUpload).
+To get started quickly with the Blazor File Upload, you can check out this [GitHub sample](https://github.com/SyncfusionExamples/Blazor-Getting-Started-Examples/tree/main/FileUpload).
{% tabcontents %}
@@ -19,15 +19,15 @@ To get started quickly with the Blazor File Upload component, review the sample
## Prerequisites
-* Review the [system requirements for Blazor components](https://blazor.syncfusion.com/documentation/system-requirements) to ensure the development environment is configured correctly.
+* [System requirements for Blazor components](https://blazor.syncfusion.com/documentation/system-requirements)
## Create a new Blazor App in Visual Studio
-Create a **Blazor Server App** using **Blazor Web App** template in Visual Studio via [Microsoft templates](https://learn.microsoft.com/en-us/aspnet/core/blazor/tooling?view=aspnetcore-7.0&pivots=vs) or the [Syncfusion® Blazor Extension](https://blazor.syncfusion.com/documentation/visual-studio-integration/template-studio). For detailed instructions, refer to [this Blazor Server App Getting Started](https://blazor.syncfusion.com/documentation/getting-started/blazor-server-side-visual-studio) documentation.
+You can create a **Blazor Server App** using the **Blazor Web App** template in Visual Studio via [Microsoft Templates](https://learn.microsoft.com/en-us/aspnet/core/blazor/tooling?view=aspnetcore-7.0&pivots=vs) or the [Syncfusion® Blazor Extension](https://blazor.syncfusion.com/documentation/visual-studio-integration/template-studio). For detailed instructions, refer to [this Blazor Server App Getting Started](https://blazor.syncfusion.com/documentation/getting-started/blazor-server-side-visual-studio) documentation.
## Install Syncfusion® Blazor Inputs and Themes NuGet in the App
-To add the **Blazor File Upload** component, open NuGet Package Manager in Visual Studio (Tools → NuGet Package Manager → Manage NuGet Packages for Solution), then search for and install [Syncfusion.Blazor.Inputs](https://www.nuget.org/packages/Syncfusion.Blazor.Inputs) and [Syncfusion.Blazor.Themes](https://www.nuget.org/packages/Syncfusion.Blazor.Themes/). Alternatively, use the following Package Manager commands.
+To add the **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](https://www.nuget.org/packages/Syncfusion.Blazor.Inputs) and [Syncfusion.Blazor.Themes](https://www.nuget.org/packages/Syncfusion.Blazor.Themes/). Alternatively, you can utilize the following package manager command to achieve the same.
{% tabs %}
{% highlight C# tabtitle="Package Manager" %}
@@ -38,7 +38,7 @@ Install-Package Syncfusion.Blazor.Themes -Version {{ site.releaseversion }}
{% endhighlight %}
{% endtabs %}
-N> Syncfusion® Blazor components are available on [nuget.org](https://www.nuget.org/packages?q=syncfusion.blazor). For a full list of packages and component details, see the [NuGet packages](https://blazor.syncfusion.com/documentation/nuget-packages) topic.
+N> Syncfusion® Blazor components are available in [nuget.org](https://www.nuget.org/packages?q=syncfusion.blazor). Refer to [NuGet packages](https://blazor.syncfusion.com/documentation/nuget-packages) topic for available NuGet packages list with component details.
{% endtabcontent %}
@@ -46,13 +46,13 @@ N> Syncfusion® Blazor components are availa
## Prerequisites
-* Review the [system requirements for Blazor components](https://blazor.syncfusion.com/documentation/system-requirements) and ensure the .NET SDK is installed.
+* [System requirements for Blazor components](https://blazor.syncfusion.com/documentation/system-requirements)
## Create a new Blazor App in Visual Studio Code
-Create a **Blazor Server App** using Visual Studio Code via [Microsoft Templates](https://learn.microsoft.com/en-us/aspnet/core/blazor/tooling?view=aspnetcore-7.0&pivots=vsc) or the [Syncfusion® Blazor Extension](https://blazor.syncfusion.com/documentation/visual-studio-code-integration/create-project). For detailed instructions, refer to [this Blazor Server App Getting Started](https://blazor.syncfusion.com/documentation/getting-started/blazor-server-side-visual-studio?tabcontent=visual-studio-code) documentation.
+You can create a **Blazor Server App** using Visual Studio Code via [Microsoft Templates](https://learn.microsoft.com/en-us/aspnet/core/blazor/tooling?view=aspnetcore-7.0&pivots=vsc) or the [Syncfusion® Blazor Extension](https://blazor.syncfusion.com/documentation/visual-studio-code-integration/create-project). For detailed instructions, refer to [this Blazor Server App Getting Started](https://blazor.syncfusion.com/documentation/getting-started/blazor-server-side-visual-studio?tabcontent=visual-studio-code) documentation.
-Alternatively, you can create a server application using the following command in the terminal (Ctrl+`). Depending on the SDK version, commands may vary between classic Blazor Server and Blazor Web App templates.
+Alternatively, you can create a server application using the following command in the terminal(Ctrl+`).
{% tabs %}
@@ -67,9 +67,9 @@ cd BlazorApp
## Install Syncfusion® Blazor Inputs and Themes NuGet in the App
-* Press Ctrl+` to open the integrated terminal in Visual Studio Code.
-* Ensure you’re in the project root directory where your `.csproj` file is located.
-* Run the following commands to install [Syncfusion.Blazor.Inputs](https://www.nuget.org/packages/Syncfusion.Blazor.Inputs) and [Syncfusion.Blazor.Themes](https://www.nuget.org/packages/Syncfusion.Blazor.Themes/) and restore dependencies.
+* Press Ctrl+` to open the integrated terminal in Visual Studio Code.
+* Ensure you’re in the project root directory where your `.csproj` file is located.
+* Run the following command to install a [Syncfusion.Blazor.Inputs](https://www.nuget.org/packages/Syncfusion.Blazor.Inputs) and [Syncfusion.Blazor.Themes](https://www.nuget.org/packages/Syncfusion.Blazor.Themes/) NuGet package and ensure all dependencies are installed.
{% tabs %}
@@ -83,7 +83,7 @@ dotnet restore
{% endtabs %}
-N> Syncfusion® Blazor components are available on [nuget.org](https://www.nuget.org/packages?q=syncfusion.blazor). Refer to the [NuGet packages](https://blazor.syncfusion.com/documentation/nuget-packages) topic for the available packages and component details.
+N> Syncfusion® Blazor components are available in [nuget.org](https://www.nuget.org/packages?q=syncfusion.blazor). Refer to [NuGet packages](https://blazor.syncfusion.com/documentation/nuget-packages) topic for available NuGet packages list with component details.
{% endtabcontent %}
@@ -91,7 +91,7 @@ N> Syncfusion® Blazor components are availa
## Prerequisites
-Install the latest [.NET SDK](https://dotnet.microsoft.com/en-us/download). If previously installed, verify the version with the following command.
+Latest version of the [.NET Core SDK](https://dotnet.microsoft.com/en-us/download). If you previously installed the SDK, you can determine the installed version by executing the following command in a command prompt (Windows) or terminal (macOS) or command shell (Linux).
{% tabs %}
{% highlight c# tabtitle=".NET CLI" %}
@@ -103,7 +103,7 @@ dotnet --version
## Create a Blazor Server App using .NET CLI
-Run the `dotnet new blazorserver` command to create a new Blazor Server app in a command prompt (Windows), terminal (macOS), or shell (Linux). Depending on the SDK version, Blazor Web App templates can also be used with server interactivity.
+Run the `dotnet new blazorserver` command to create a new Blazor Server application in a command prompt (Windows) or terminal (macOS) or command shell (Linux).
{% tabs %}
{% highlight c# tabtitle=".NET CLI" %}
@@ -114,11 +114,11 @@ cd BlazorApp
{% endhighlight %}
{% endtabs %}
-This command creates a new Blazor Server app in a directory named `BlazorApp` at your current location. See the [Create Blazor app](https://dotnet.microsoft.com/en-us/learn/aspnet/blazor-tutorial/create) and [dotnet new](https://learn.microsoft.com/en-us/dotnet/core/tools/dotnet-new) topics for more details.
+This command creates a new Blazor app project and places it in a new directory called `BlazorApp` inside your current location. See [Create Blazor app topic](https://dotnet.microsoft.com/en-us/learn/aspnet/blazor-tutorial/create) and [dotnet new CLI command](https://learn.microsoft.com/en-us/dotnet/core/tools/dotnet-new) topics for more details.
## Install Syncfusion® Blazor Inputs and Themes NuGet in the App
-Use the .NET CLI to add the **Blazor File Upload** component packages. Run the following commands in a command prompt (Windows) or terminal (Linux and macOS) to install [Syncfusion.Blazor.Inputs](https://www.nuget.org/packages/Syncfusion.Blazor.Inputs/) and [Syncfusion.Blazor.Themes](https://www.nuget.org/packages/Syncfusion.Blazor.Themes/). For more information, see [Install and manage packages using the dotnet CLI](https://learn.microsoft.com/en-us/nuget/consume-packages/install-use-packages-dotnet-cli).
+Here's an example of how to add the **Blazor File Upload** component in the application using the following command in the command prompt (Windows) or terminal (Linux and macOS) to install a [Syncfusion.Blazor.Inputs](https://www.nuget.org/packages/Syncfusion.Blazor.Inputs/) and [Syncfusion.Blazor.Themes](https://www.nuget.org/packages/Syncfusion.Blazor.Themes/) NuGet package. See [Install and manage packages using the dotnet CLI](https://learn.microsoft.com/en-us/nuget/consume-packages/install-use-packages-dotnet-cli) topics for more details.
{% tabs %}
{% highlight c# tabtitle=".NET CLI" %}
@@ -130,7 +130,7 @@ dotnet restore
{% endhighlight %}
{% endtabs %}
-N> Syncfusion® Blazor components are available on [nuget.org](https://www.nuget.org/packages?q=syncfusion.blazor). Refer to the [NuGet packages](https://blazor.syncfusion.com/documentation/nuget-packages) topic for the available packages and component details.
+N> Syncfusion® Blazor components are available in [nuget.org](https://www.nuget.org/packages?q=syncfusion.blazor). Refer to [NuGet packages](https://blazor.syncfusion.com/documentation/nuget-packages) topic for available NuGet packages list with component details.
{% endtabcontent %}
@@ -149,7 +149,7 @@ Open the **~/_Imports.razor** file and import the `Syncfusion.Blazor` and `Syncf
## Register Syncfusion® Blazor Service
-Register the Syncfusion® Blazor service in the **~/Program.cs** file of your Blazor Server app.
+Register the Syncfusion® Blazor Service in the **~/Program.cs** file of your Blazor Server App.
{% tabs %}
{% highlight C# tabtitle="~/Program.cs" hl_lines="3 10" %}
@@ -172,7 +172,7 @@ builder.Services.AddSyncfusionBlazor();
## Add stylesheet and script resources
-The theme stylesheet and script are available via [Static Web Assets](https://blazor.syncfusion.com/documentation/appearance/themes#static-web-assets). Include the stylesheet in the `` and the script reference at the end of the `` in the **App.razor** file as shown below.
+The theme stylesheet and script can be accessed from NuGet through [Static Web Assets](https://blazor.syncfusion.com/documentation/appearance/themes#static-web-assets). Include the stylesheet and script in the `` and the script reference at the end of the `` in the **App.razor** file as shown below:
```html
@@ -186,17 +186,23 @@ The theme stylesheet and script are available via [Static Web Assets](https://bl
//Blazor File Upload Component script reference.
-
+
```
-N> See the [Blazor Themes](https://blazor.syncfusion.com/documentation/appearance/themes) topic for options to reference themes ([Static Web Assets](https://blazor.syncfusion.com/documentation/appearance/themes#static-web-assets), [CDN](https://blazor.syncfusion.com/documentation/appearance/themes#cdn-reference), and [CRG](https://blazor.syncfusion.com/documentation/common/custom-resource-generator)). For adding scripts, refer to [Adding Script Reference](https://blazor.syncfusion.com/documentation/common/adding-script-references).
+N> Check out the [Blazor Themes](https://blazor.syncfusion.com/documentation/appearance/themes) topic to discover various methods ([Static Web Assets](https://blazor.syncfusion.com/documentation/appearance/themes#static-web-assets), [CDN](https://blazor.syncfusion.com/documentation/appearance/themes#cdn-reference), and [CRG](https://blazor.syncfusion.com/documentation/common/custom-resource-generator)) for referencing themes in your Blazor application. Also, check out the [Adding Script Reference](https://blazor.syncfusion.com/documentation/common/adding-script-references) topic to learn different approaches for adding script references in your Blazor application.
+
+## Add Syncfusion® Blazor File Upload component
+
+The Syncfusion Blazor File Upload 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.
-## Add Blazor File Upload component
+### Simple Code to render a Usable File Upload Component
-Add the Syncfusion® Blazor File Upload component in the **~/Components/Pages/Home.razor** file. If the interactivity location is set to `Per page/component`, define a render mode at the top of the `Home.razor` page.
+The most basic way to render the File Upload component is by adding the `` tag to your `.razor` page. By default, this component provides a clean interface for users to select files locally.
-N> If the interactivity location is set to `Global` and the **Render Mode** is `Server`, the render mode is configured in the `App.razor` file by default.
+Add the Syncfusion® Blazor File Upload component in the **~/Components/Pages/Home.razor** file. If an interactivity location as `per page/component`, define a render mode at the top of the `Home.razor` page.
+
+N> If an Interactivity Location is set to `Global` and the **Render Mode** is set to `Server`, the render mode is configured in the `App.razor` file by default.
```
@* desired render mode define here *@
@@ -211,41 +217,60 @@ N> If the interactivity location is set to `Global` and the **Render Mode** is `
{% endhighlight %}
{% endtabs %}
-* Press Ctrl+F5 (Windows) or ⌘+F5 (macOS) to launch the application. This renders the Syncfusion® Blazor File Upload component in the default web browser.
+* 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.
+
+{% previewsample "https://blazorplayground.syncfusion.com/embed/LXBJXsrOqbMEOurR?appbar=false&editor=false&result=true&errorlist=false&theme=bootstrap5" %}
-{% previewsample "https://blazorplayground.syncfusion.com/embed/LXBJXsrOqbMEOurR?appbar=false&editor=false&result=true&errorlist=false&theme=bootstrap5" backgroundimage "[Blazor FileUpload Component](./images/blazor-fileupload-component.png)" %}
+
-## Without server-side API endpoint
+## Use ValueChange Event
-Upload the files and files of folders in the Blazor application without specifying the server-side API end point using [AsyncSettings](https://help.syncfusion.com/cr/blazor/Syncfusion.Blazor.Inputs.UploaderAsyncSettings.html).
+The [`ValueChange`](https://help.syncfusion.com/cr/blazor/Syncfusion.Blazor.Inputs.UploaderEvents.html#Syncfusion_Blazor_Inputs_UploaderEvents_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.
-### Save and Remove actions
+### Code Example
-Access the uploaded files as streams in the [ValueChange](https://help.syncfusion.com/cr/blazor/Syncfusion.Blazor.Inputs.UploaderEvents.html#Syncfusion_Blazor_Inputs_UploaderEvents_ValueChange) event argument. Implement save logic in the ValueChange event to write files to the desired location. The following sample shows the save action pattern.
+This example demonstrates how to use the [`ValueChange`](https://help.syncfusion.com/cr/blazor/Syncfusion.Blazor.Inputs.UploaderEvents.html#Syncfusion_Blazor_Inputs_UploaderEvents_ValueChange) event to save uploaded files directly to a local directory when the [`AutoUpload`](https://help.syncfusion.com/cr/blazor/Syncfusion.Blazor.Inputs.SfUploader.html#Syncfusion_Blazor_Inputs_SfUploader_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.
{% tabs %}
{% highlight razor %}
@using Syncfusion.Blazor.Inputs
+@using System.IO
+
+
@code {
private async Task OnChange(UploadChangeEventArgs args)
{
try
{
- foreach (var file in args.Files)
+ foreach (var fileEntry 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();
+ // 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(ex.Message);
+ Console.WriteLine($"Error saving file: {ex.Message}");
}
}
}
@@ -253,20 +278,71 @@ Access the uploaded files as streams in the [ValueChange](https://help.syncfusio
{% endhighlight %}
{% endtabs %}
-
+N> When saving files directly in a Blazor Server application using [`ValueChange`](https://help.syncfusion.com/cr/blazor/Syncfusion.Blazor.Inputs.UploaderEvents.html#Syncfusion_Blazor_Inputs_UploaderEvents_ValueChange) and [`AutoUpload`](https://help.syncfusion.com/cr/blazor/Syncfusion.Blazor.Inputs.SfUploader.html#Syncfusion_Blazor_Inputs_SfUploader_AutoUpload), 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/uploads` in this example) exists or is created programmatically. In a production environment, consider secure storage solutions for uploaded files.
+
+{% previewsample "https://blazorplayground.syncfusion.com/embed/hDVyZkrqBvaSlvht?appbar=false&editor=false&result=true&errorlist=false&theme=bootstrap5" %}
+
+
+
+
+## Memory stream
-When the remove icon is selected in the file list, the [OnRemove](https://help.syncfusion.com/cr/blazor/Syncfusion.Blazor.Inputs.UploaderEvents.html#Syncfusion_Blazor_Inputs_UploaderEvents_OnRemove) event provides the file name as an argument. Implement the remove handler in the OnRemove event to delete the file from the chosen location. The following sample illustrates the remove action pattern.
+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.
+
+### Code Example
+
+This example demonstrates how to read the content of an uploaded file into a [MemoryStream Class](https://learn.microsoft.com/en-us/dotnet/api/system.io.memorystream)`. 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.
{% tabs %}
-{% highlight cshtml %}
+{% highlight razor %}
+
+@using Syncfusion.Blazor.Inputs
+@using System.IO
-Private void onRemove(RemovingEventArgs args)
+
+
+
+
+@if (!string.IsNullOrEmpty(base64Image))
{
- foreach(var removeFile in args.FilesData)
+
Uploaded Image Preview (Base64)
+
+}
+
+@code {
+ private string base64Image;
+
+ private async Task OnValueChangeMemoryStream(UploadChangeEventArgs args)
{
- if (File.Exists(Path.Combine(@"rootPath", removeFile.Name)))
+ base64Image = string.Empty; // Clear previous image
+
+ foreach (var fileEntry in args.Files)
{
- File.Delete(Path.Combine(@"rootPath", removeFile.Name))
+ 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}");
+ }
}
}
}
@@ -274,114 +350,145 @@ Private void onRemove(RemovingEventArgs args)
{% endhighlight %}
{% endtabs %}
-## With server-side API endpoint
+N> When using `MemoryStream` for 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. The `long.MaxValue` in `OpenReadStream` indicates the maximum buffer size. In a Blazor Server app, `Stream` operations occur on the server.
+
+{% previewsample "https://blazorplayground.syncfusion.com/embed/BjreNaLUhdwxzvHS?appbar=false&editor=false&result=true&errorlist=false&theme=bootstrap5" %}
+
+
-The upload process requires save and remove action URL to manage the upload process in the server.
-N> * The save action is necessary to handle the upload operation.
- * The remove action is optional, one can handle the removed files from server.
+## Created Event
-The save action handler upload the files that needs to be specified in the [SaveUrl](https://help.syncfusion.com/cr/blazor/Syncfusion.Blazor.Inputs.UploaderAsyncSettings.html#Syncfusion_Blazor_Inputs_UploaderAsyncSettings_SaveUrl) property.
+The [`Created`](https://help.syncfusion.com/cr/blazor/Syncfusion.Blazor.Inputs.UploaderEvents.html#Syncfusion_Blazor_Inputs_UploaderEvents_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.
-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.
+### Code Example
-Specify the remove endpoint in the [RemoveUrl](https://help.syncfusion.com/cr/blazor/Syncfusion.Blazor.Inputs.UploaderAsyncSettings.html#Syncfusion_Blazor_Inputs_UploaderAsyncSettings_RemoveUrl) property. The [OnActionComplete](https://help.syncfusion.com/cr/blazor/Syncfusion.Blazor.Inputs.UploaderEvents.html#Syncfusion_Blazor_Inputs_UploaderEvents_OnActionComplete) event is triggered after all selected files have been processed (uploaded successfully or failed).
+This example shows how to use the [`Created`](https://help.syncfusion.com/cr/blazor/Syncfusion.Blazor.Inputs.UploaderEvents.html#Syncfusion_Blazor_Inputs_UploaderEvents_Created) event to add a custom message or dynamically change some aspect of the uploader's appearance right after it's created.
{% tabs %}
-{% highlight cshtml %}
+{% highlight razor %}
-[Route("api/[controller]")]
-public class SampleDataController : Controller
-{
- public string uploads = ".\\Uploaded Files"; // replace with your directory path
+@using Syncfusion.Blazor.Inputs
- [HttpPost("[action]")]
- public async Task Save(IFormFile UploadFiles) // Save the uploaded file here
- {
- if (UploadFiles.Length > 0)
- {
- //Create directory if not exists
- if (!Directory.Exists(uploads))
- {
- Directory.CreateDirectory(uploads);
- }
+
+
+
- var filePath = Path.Combine(uploads, UploadFiles.FileName);
- if (System.IO.File.Exists(filePath))
- {
- //Return conflict status code
- return new StatusCodeResult(StatusCodes.Status409Conflict);
- }
- using (var fileStream = new FileStream(filePath, FileMode.Create))
- {
- //Save the uploaded file to server
- await UploadFiles.CopyToAsync(fileStream);
- }
- }
- return Ok();
- }
+
@statusMessage
+@code {
+ private string statusMessage = "Uploader not yet created.";
- [HttpPost("[action]")]
- public void Remove(string UploadFiles) // Delete the uploaded file here
+ private void OnUploaderCreated()
{
- if(UploadFiles != null)
- {
- var filePath = Path.Combine(uploads, UploadFiles);
- if (System.IO.File.Exists(filePath))
- {
- //Delete the file from server
- System.IO.File.Delete(filePath);
- }
- }
+ 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");
}
}
{% endhighlight %}
{% endtabs %}
-The [OnFailure](https://help.syncfusion.com/cr/blazor/Syncfusion.Blazor.Inputs.UploaderEvents.html#Syncfusion_Blazor_Inputs_UploaderEvents_OnFailure) event is triggered when there is a failure in the AJAX request during uploading or removing files. Use it to handle and respond to errors that occur during the upload or removal process.
+N> The [`Created`](https://help.syncfusion.com/cr/blazor/Syncfusion.Blazor.Inputs.UploaderEvents.html#Syncfusion_Blazor_Inputs_UploaderEvents_Created) event 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.
+
+{% previewsample "https://blazorplayground.syncfusion.com/embed/VtLyNuVUBGtPZrdo?appbar=false&editor=false&result=true&errorlist=false&theme=bootstrap5" %}
+
+
+
+
+## File Selected Event
+
+The [`FileSelected Event`](https://help.syncfusion.com/cr/blazor/Syncfusion.Blazor.Inputs.UploaderEvents.html#Syncfusion_Blazor_Inputs_UploaderEvents_FileSelected)event is triggered when files are chosen from the file explorer dialog, but **before** the [`ValueChange`](https://help.syncfusion.com/cr/blazor/Syncfusion.Blazor.Inputs.UploaderEvents.html#Syncfusion_Blazor_Inputs_UploaderEvents_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.
+
+### Code Example
+
+This example demonstrates how to use the [FileSelected Event](https://help.syncfusion.com/cr/blazor/Syncfusion.Blazor.Inputs.UploaderEvents.html#Syncfusion_Blazor_Inputs_UploaderEvents_FileSelected) event to prevent files larger than a certain size.
{% tabs %}
{% highlight razor %}
-
-
-
+@using Syncfusion.Blazor.Inputs
+@using System.Linq
+
+
+
+
@validationMessage
+
@code {
- private void OnFailureHandler(FailureEventArgs args)
- {
- // Here, you can customize your code.
- }
- private void OnActionCompleteHandler(ActionCompleteEventArgs args)
+ private string validationMessage = "";
+ private readonly long MaxFileSize = 1024 * 1024; // 1 MB
+
+ private void OnFileSelected(SelectedEventArgs args)
{
- // Here, you can customize your code.
+ 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.");
+ }
}
}
{% endhighlight %}
{% endtabs %}
-## Configure allowed file types
+N> Setting `args.Cancel = true` in the `FileSelected` event will prevent the file (or files if `args.Files` contains 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.
+
+{% previewsample "https://blazorplayground.syncfusion.com/embed/BDLIZuBUVwEJoJpz?appbar=false&editor=false&result=true&errorlist=false&theme=bootstrap5" %}
+
+
+
+
+## OnFileListRender
-Allow only specific files to be uploaded using the [AllowedExtensions](https://help.syncfusion.com/cr/blazor/Syncfusion.Blazor.Inputs.UploaderModel.html#Syncfusion_Blazor_Inputs_UploaderModel_AllowedExtensions) property. Provide extensions as a comma-separated list. The Uploader filters selected or dropped files to match the specified types and then processes the upload operation. Client-side validation occurs when a value is specified for the underlying input element’s accept attribute.
+The [`OnFileListRender`](https://help.syncfusion.com/cr/blazor/Syncfusion.Blazor.Inputs.UploaderEvents.html#Syncfusion_Blazor_Inputs_UploaderEvents_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.
+
+### Code Example
+
+This example demonstrates how to use [`OnFileListRender`](https://help.syncfusion.com/cr/blazor/Syncfusion.Blazor.Inputs.UploaderEvents.html#Syncfusion_Blazor_Inputs_UploaderEvents_OnFileListRender)
{% tabs %}
{% highlight razor %}
-
+@using Syncfusion.Blazor.Inputs
+
+
+
+
+
+
+@code {
+ SfUploader fileobj;
+ private void OnFileListRenderHandler(FileListRenderingEventArgs args)
+ {
+
+ }
+}
{% endhighlight %}
{% endtabs %}
-{% previewsample "https://blazorplayground.syncfusion.com/embed/rXhzDsrOqbKVNviI?appbar=false&editor=false&result=true&errorlist=false&theme=bootstrap5" backgroundimage "[Allowing Specific Files in Blazor FileUpload](./images/blazor-fileupload-allow-specific-file.png)" %}
N> [View Sample in GitHub](https://github.com/SyncfusionExamples/Blazor-Getting-Started-Examples/tree/main/FileUpload).
## See also
-1. [Getting Started with Syncfusion® Blazor for client-side in .NET Core CLI](https://blazor.syncfusion.com/documentation/getting-started/blazor-webassembly-dotnet-cli)
-2. [Getting Started with Syncfusion® Blazor for client-side in Visual Studio](https://blazor.syncfusion.com/documentation/getting-started/blazor-webassembly-visual-studio)
-3. [Getting Started with Syncfusion® Blazor for server-side in .NET Core CLI](https://blazor.syncfusion.com/documentation/getting-started/blazor-server-side-dotnet-cli)
-4. [Getting Started with Syncfusion® File Upload in Blazor WebAssembly using Visual Studio](https://blazor.syncfusion.com/documentation/file-upload/how-to/getting-started-with-blazor-webassembly)
\ No newline at end of file
+1. [Getting Started with Syncfusion® Blazor for client-side in .NET Core CLI](https://blazor.syncfusion.com/documentation/getting-started/blazor-webassembly-dotnet-cli)
+2. [Getting Started with Syncfusion® Blazor for client-side in Visual Studio](https://blazor.syncfusion.com/documentation/getting-started/blazor-webassembly-visual-studio)
+3. [Getting Started with Syncfusion® Blazor for server-side in .NET Core CLI](https://blazor.syncfusion.com/documentation/getting-started/blazor-server-side-dotnet-cli)
+4. [Getting Started with Syncfusion® File Upload in Blazor WebAssembly using Visual Studio](https://blazor.syncfusion.com/documentation/file-upload/how-to/getting-started-with-blazor-webassembly)
+5. [How to convert images to Base64 string with Blazor File Upload](https://support.syncfusion.com/kb/article/21178/how-to-convert-images-to-base64-string-with-blazor-file-upload)
diff --git a/blazor/file-upload/getting-started-with-web-app.md b/blazor/file-upload/getting-started-with-web-app.md
index c3c31f179f..ee28c98730 100644
--- a/blazor/file-upload/getting-started-with-web-app.md
+++ b/blazor/file-upload/getting-started-with-web-app.md
@@ -9,7 +9,7 @@ documentation: ug
# Getting Started with Blazor File Upload Component in Web App
-This section explains how to include the [Blazor File Upload](https://www.syncfusion.com/blazor-components/blazor-file-upload) component in a Blazor Web App using Visual Studio, Visual Studio Code, and the .NET CLI.
+This section briefly explains how to include the [Blazor File Upload](https://www.syncfusion.com/blazor-components/blazor-file-upload) component in your Blazor Web App using [Visual Studio](https://visualstudio.microsoft.com/vs/), Visual Studio Code, and .NET CLI.
{% tabcontents %}
@@ -17,23 +17,21 @@ This section explains how to include the [Blazor File Upload](https://www.syncfu
## Prerequisites
-* [System requirements for Blazor components](https://blazor.syncfusion.com/documentation/system-requirements)
+* [System requirements for Blazor components](https://blazor.syncfusion.com/documentation/system-requirements)
## Create a new Blazor Web App in Visual Studio
-Create a **Blazor Web App** using Visual Studio 2022 via [Microsoft templates](https://learn.microsoft.com/en-us/aspnet/core/blazor/tooling?view=aspnetcore-8.0&pivots=vs) or the [Syncfusion® Blazor Extension](https://blazor.syncfusion.com/documentation/visual-studio-integration/template-studio). For detailed instructions, refer to [this Blazor Web App Getting Started](https://blazor.syncfusion.com/documentation/getting-started/blazor-web-app) documentation.
+You can create a **Blazor Web App** using Visual Studio 2022 via [Microsoft Templates](https://learn.microsoft.com/en-us/aspnet/core/blazor/tooling?view=aspnetcore-8.0&pivots=vs) or the [Syncfusion® Blazor Extension](https://blazor.syncfusion.com/documentation/visual-studio-integration/template-studio). For detailed instructions, refer to [this Blazor Web App Getting Started](https://blazor.syncfusion.com/documentation/getting-started/blazor-web-app) documentation.
-Configure the appropriate [interactive render mode](https://learn.microsoft.com/en-us/aspnet/core/blazor/components/render-modes?view=aspnetcore-8.0#render-modes) and [interactivity location](https://learn.microsoft.com/en-us/aspnet/core/blazor/tooling?view=aspnetcore-8.0&pivots=vs) when creating the project.
-
-
+You need to configure the corresponding [Interactive render mode](https://learn.microsoft.com/en-us/aspnet/core/blazor/components/render-modes?view=aspnetcore-8.0#render-modes) and [Interactivity location](https://learn.microsoft.com/en-us/aspnet/core/blazor/tooling?view=aspnetcore-8.0&pivots=vs) while creating a Blazor Web Application.
## Install Syncfusion® Blazor Inputs and Themes NuGet in the Blazor Web App
-To add the **Blazor File Upload** component, open NuGet Package Manager in Visual Studio (Tools → NuGet Package Manager → Manage NuGet Packages for Solution), then install [Syncfusion.Blazor.Inputs](https://www.nuget.org/packages/Syncfusion.Blazor.Inputs/) and [Syncfusion.Blazor.Themes](https://www.nuget.org/packages/Syncfusion.Blazor.Themes/).
+To add the **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](https://www.nuget.org/packages/Syncfusion.Blazor.Inputs/) and [Syncfusion.Blazor.Themes](https://www.nuget.org/packages/Syncfusion.Blazor.Themes/).
-If using the `WebAssembly` or `Auto` render modes, install the Syncfusion® Blazor NuGet packages in the client project.
+If you utilize `WebAssembly` or `Auto` render modes in the Blazor Web App, you need to install Syncfusion® Blazor components NuGet packages within the client project.
-Alternatively, use the following Package Manager commands.
+Alternatively, you can utilize the following package manager command to achieve the same.
{% tabs %}
{% highlight C# tabtitle="Package Manager" %}
@@ -44,7 +42,7 @@ Install-Package Syncfusion.Blazor.Themes -Version {{ site.releaseversion }}
{% endhighlight %}
{% endtabs %}
-N> Syncfusion® Blazor components are available on [nuget.org](https://www.nuget.org/packages?q=syncfusion.blazor). For a full list of packages and component details, see the [NuGet packages](https://blazor.syncfusion.com/documentation/nuget-packages) topic.
+N> Syncfusion® Blazor components are available in [nuget.org](https://www.nuget.org/packages?q=syncfusion.blazor). Refer to [NuGet packages](https://blazor.syncfusion.com/documentation/nuget-packages) topic for available NuGet packages list with component details.
{% endtabcontent %}
@@ -52,18 +50,18 @@ N> Syncfusion® Blazor components are availa
## Prerequisites
-* [System requirements for Blazor components](https://blazor.syncfusion.com/documentation/system-requirements)
+* [System requirements for Blazor components](https://blazor.syncfusion.com/documentation/system-requirements)
## Create a new Blazor Web App in Visual Studio Code
-Create a **Blazor Web App** using Visual Studio Code via [Microsoft templates](https://learn.microsoft.com/en-us/aspnet/core/blazor/tooling?view=aspnetcore-8.0&pivots=vsc) or the [Syncfusion® Blazor Extension](https://blazor.syncfusion.com/documentation/visual-studio-code-integration/create-project). For detailed instructions, refer to [this Blazor Web App Getting Started](https://blazor.syncfusion.com/documentation/getting-started/blazor-web-app?tabcontent=visual-studio-code) documentation.
+You can create a **Blazor Web App** using Visual Studio Code via [Microsoft Templates](https://learn.microsoft.com/en-us/aspnet/core/blazor/tooling?view=aspnetcore-8.0&pivots=vsc) or the [Syncfusion® Blazor Extension](https://blazor.syncfusion.com/documentation/visual-studio-code-integration/create-project). For detailed instructions, refer to [this Blazor Web App Getting Started](https://blazor.syncfusion.com/documentation/getting-started/blazor-web-app?tabcontent=visual-studio-code) documentation.
-Configure the appropriate interactive render mode and interactivity location during setup. For details, see the [interactive render mode documentation](https://blazor.syncfusion.com/documentation/common/interactive-render-mode).
+Configure the appropriate interactive render mode and interactivity location when setting up a Blazor Web Application. For detailed information, refer to the [interactive render mode documentation](https://blazor.syncfusion.com/documentation/common/interactive-render-mode).
-For example, to create a Blazor Web App with the `Auto` interactive render mode:
+For example, in a Blazor Web App with the `Auto` interactive render mode, use the following commands.
{% tabs %}
-{% highlight c# tabtitle="Blazor Web App" %}
+{% highlight C# tabtitle="Blazor Web App" %}
dotnet new blazor -o BlazorWebApp -int Auto
cd BlazorWebApp
@@ -72,17 +70,19 @@ cd BlazorWebApp.Client
{% endhighlight %}
{% endtabs %}
+N> For more information on creating a **Blazor Web App** with various interactive modes and locations, refer to this [link](https://blazor.syncfusion.com/documentation/getting-started/blazor-web-app?tabcontent=visual-studio-code#render-interactive-modes).
+
## Install Syncfusion® Blazor Inputs and Themes NuGet in the App
-If using the `WebAssembly` or `Auto` render modes, install Syncfusion® Blazor NuGet packages in the client project.
+If you utilize `WebAssembly` or `Auto` render modes in the Blazor Web App, you need to install Syncfusion® Blazor components NuGet packages within the client project.
-* Press Ctrl+` to open the integrated terminal in Visual Studio Code.
-* Ensure you are in the project directory that contains the target `.csproj` file.
-* Run the following commands to install [Syncfusion.Blazor.Inputs](https://www.nuget.org/packages/Syncfusion.Blazor.Inputs) and [Syncfusion.Blazor.Themes](https://www.nuget.org/packages/Syncfusion.Blazor.Themes/), then restore packages.
+* Press Ctrl+` to open the integrated terminal in Visual Studio Code.
+* Ensure you’re in the project root directory where your `.csproj` file is located.
+* Run the following command to install a [Syncfusion.Blazor.Inputs](https://www.nuget.org/packages/Syncfusion.Blazor.Inputs) and [Syncfusion.Blazor.Themes](https://www.nuget.org/packages/Syncfusion.Blazor.Themes/) NuGet package and ensure all dependencies are installed.
{% tabs %}
-{% highlight c# tabtitle="Package Manager" %}
+{% highlight C# tabtitle="Package Manager" %}
dotnet add package Syncfusion.Blazor.Inputs -v {{ site.releaseversion }}
dotnet add package Syncfusion.Blazor.Themes -v {{ site.releaseversion }}
@@ -92,7 +92,7 @@ dotnet restore
{% endtabs %}
-N> Syncfusion® Blazor components are available on [nuget.org](https://www.nuget.org/packages?q=syncfusion.blazor). For the complete package list with component details, see the [NuGet packages](https://blazor.syncfusion.com/documentation/nuget-packages) topic.
+N> Syncfusion® Blazor components are available in [nuget.org](https://www.nuget.org/packages?q=syncfusion.blazor). Refer to [NuGet packages](https://blazor.syncfusion.com/documentation/nuget-packages) topic for available NuGet packages list with component details.
{% endtabcontent %}
@@ -100,26 +100,26 @@ N> Syncfusion® Blazor components are availa
## Prerequisites
-Install the latest [.NET SDK](https://dotnet.microsoft.com/en-us/download). To check the installed version, run the following command in a terminal or command prompt:
+Latest version of the [.NET Core SDK](https://dotnet.microsoft.com/en-us/download). If you previously installed the SDK, you can determine the installed version by executing the following command in a command prompt (Windows) or terminal (macOS) or command shell (Linux).
{% tabs %}
-{% highlight c# tabtitle=".NET CLI" %}
+{% highlight C# tabtitle=".NET CLI" %}
dotnet --version
{% endhighlight %}
{% endtabs %}
-## Create a Blazor Web App using .NET CLI
+## Create a Blazor Web project using .NET CLI
-Run the following command to create a new Blazor Web App. For step-by-step guidance, see the [Blazor Web App getting started](https://blazor.syncfusion.com/documentation/getting-started/blazor-web-app?tabcontent=.net-cli) documentation.
+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 [this Blazor Web App Getting Started](https://blazor.syncfusion.com/documentation/getting-started/blazor-web-app?tabcontent=.net-cli) documentation.
-Configure the appropriate interactive render mode and interactivity location during setup. For details, see the [interactive render mode documentation](https://blazor.syncfusion.com/documentation/common/interactive-render-mode).
+Configure the appropriate interactive render mode and interactivity location when setting up a Blazor Web Application. For detailed information, refer to the [interactive render mode documentation](https://blazor.syncfusion.com/documentation/common/interactive-render-mode).
-For example, to create a Blazor Web App with the `Auto` interactive render mode:
+For example, in a Blazor Web App with `Auto` interactive render mode, use the following commands:
{% tabs %}
-{% highlight c# tabtitle=".NET CLI" %}
+{% highlight C# tabtitle=".NET CLI" %}
dotnet new blazor -o BlazorApp -int Auto
cd BlazorApp
@@ -128,16 +128,16 @@ cd BlazorApp.Client
{% endhighlight %}
{% endtabs %}
-This command creates a new Blazor Web App in a directory named `BlazorApp` within the current location. See the [Create Blazor app](https://dotnet.microsoft.com/en-us/learn/aspnet/blazor-tutorial/create) and [dotnet new](https://learn.microsoft.com/en-us/aspnet/core/blazor/tooling?pivots=linux-macos&view=aspnetcore-8.0) topics for more details.
+This command creates a new Blazor Web app project and places it in a new directory called `BlazorApp` inside your current location. See [Create Blazor app topic](https://dotnet.microsoft.com/en-us/learn/aspnet/blazor-tutorial/create) and [dotnet new CLI command](https://learn.microsoft.com/en-us/aspnet/core/blazor/tooling?pivots=linux-macos&view=aspnetcore-8.0) topics for more details.
## Install Syncfusion® Blazor Inputs and Themes NuGet in the App
-Here's an example of how to add **Blazor File Upload** component in the application using the following command in the command prompt (Windows) or terminal (Linux and macOS) to install a [Syncfusion.Blazor.Inputs](https://www.nuget.org/packages/Syncfusion.Blazor.Inputs/) and [Syncfusion.Blazor.Themes](https://www.nuget.org/packages/Syncfusion.Blazor.Themes/) NuGet package. See [Install and manage packages using the dotnet CLI](https://learn.microsoft.com/en-us/nuget/consume-packages/install-use-packages-dotnet-cli) topics for more details.
+Here's an example of how to add the **Blazor File Upload** component in the application using the following command in the command prompt (Windows) or terminal (Linux and macOS) to install a [Syncfusion.Blazor.Inputs](https://www.nuget.org/packages/Syncfusion.Blazor.Inputs/) and [Syncfusion.Blazor.Themes](https://www.nuget.org/packages/Syncfusion.Blazor.Themes/) NuGet package. See [Install and manage packages using the dotnet CLI](https://learn.microsoft.com/en-us/nuget/consume-packages/install-use-packages-dotnet-cli) topics for more details.
-If using the `WebAssembly` or `Auto` render modes, install packages in the client project.
+If you utilize `WebAssembly` or `Auto` render modes in the Blazor Web App, you need to install Syncfusion® Blazor components NuGet packages within the client project.
{% tabs %}
-{% highlight c# tabtitle=".NET CLI" %}
+{% highlight C# tabtitle=".NET CLI" %}
dotnet add package Syncfusion.Blazor.Inputs --version {{ site.releaseversion }}
dotnet add package Syncfusion.Blazor.Themes --version {{ site.releaseversion }}
@@ -146,7 +146,7 @@ dotnet restore
{% endhighlight %}
{% endtabs %}
-N> Syncfusion® Blazor components are available on [nuget.org](https://www.nuget.org/packages?q=syncfusion.blazor). For a complete package list, see the [NuGet packages](https://blazor.syncfusion.com/documentation/nuget-packages) topic.
+N> Syncfusion® Blazor components are available in [nuget.org](https://www.nuget.org/packages?q=syncfusion.blazor). Refer to [NuGet packages](https://blazor.syncfusion.com/documentation/nuget-packages) topic for available NuGet packages list with component details.
{% endtabcontent %}
@@ -154,7 +154,7 @@ N> Syncfusion® Blazor components are availa
## Add Import Namespaces
-Open the **~/_Imports.razor** file in the client project and import the `Syncfusion.Blazor` and `Syncfusion.Blazor.Inputs` namespaces.
+Open the **~/_Imports.razor** file from the client project and import the `Syncfusion.Blazor` and `Syncfusion.Blazor.Inputs` namespaces.
{% tabs %}
{% highlight C# tabtitle="~/_Imports.razor" %}
@@ -165,14 +165,14 @@ Open the **~/_Imports.razor** file in the client project and import the `Syncfus
{% endhighlight %}
{% endtabs %}
-## Register Syncfusion® Blazor Service
+
Register Syncfusion® Blazor Service
-Register the Syncfusion® Blazor service in the **~/Program.cs** file of the Blazor Web App.
+Register the Syncfusion® Blazor Service in the **~/Program.cs** file of your Blazor Web App.
-If the app uses `WebAssembly` or `Auto` interactive render modes, register the Syncfusion® Blazor service in both the main Server project and the associated `.Client` project.
+If your Blazor Web App uses `WebAssembly` or `Auto` interactive render modes, you must register the Syncfusion® Blazor service in the **~/Program.cs** files of the main `server` project and associated `.Client` project.
{% tabs %}
-{% highlight c# tabtitle="Server(~/_Program.cs)" hl_lines="3 11" %}
+{% highlight C# tabtitle="Server (~/Program.cs)" hl_lines="3 11" %}
...
...
@@ -190,7 +190,7 @@ var app = builder.Build();
....
{% endhighlight %}
-{% highlight c# tabtitle="Client(~/_Program.cs)" hl_lines="2 5" %}
+{% highlight C# tabtitle="Client (~/Program.cs)" hl_lines="2 5" %}
...
using Syncfusion.Blazor;
@@ -203,9 +203,9 @@ await builder.Build().RunAsync();
{% endhighlight %}
{% endtabs %}
-## Add stylesheet and script resources
+
Add stylesheet and script resources
-The theme stylesheet and script are available via [Static Web Assets](https://blazor.syncfusion.com/documentation/appearance/themes#static-web-assets). Add the stylesheet in the `` and the script at the end of the `` in **~/Components/App.razor** as shown below. When using the `WebAssembly` or `Auto` render modes, ensure the client project also references the required resources.
+The theme stylesheet and script can be accessed from NuGet through [Static Web Assets](https://blazor.syncfusion.com/documentation/appearance/themes#static-web-assets). Include the stylesheet reference in the `` section and the script reference at the end of the `` in the **~/Components/App.razor** file as shown below:
```html
@@ -217,16 +217,20 @@ The theme stylesheet and script are available via [Static Web Assets](https://bl
....
- //Blazor File Upload Component script reference.
-
+
+
```
-N> See the [Blazor Themes](https://blazor.syncfusion.com/documentation/appearance/themes) topic for ways to reference themes ([Static Web Assets](https://blazor.syncfusion.com/documentation/appearance/themes#static-web-assets), [CDN](https://blazor.syncfusion.com/documentation/appearance/themes#cdn-reference), and [CRG](https://blazor.syncfusion.com/documentation/common/custom-resource-generator)). For adding scripts, see [Adding Script Reference](https://blazor.syncfusion.com/documentation/common/adding-script-references). If using the consolidated Syncfusion script, separate per-component scripts are typically not required.
+N> Check out the [Blazor Themes](https://blazor.syncfusion.com/documentation/appearance/themes) topic to discover various methods ([Static Web Assets](https://blazor.syncfusion.com/documentation/appearance/themes#static-web-assets), [CDN](https://blazor.syncfusion.com/documentation/appearance/themes#cdn-reference), and [CRG](https://blazor.syncfusion.com/documentation/common/custom-resource-generator)) for referencing themes in your Blazor application. Also, check out the [Adding Script Reference](https://blazor.syncfusion.com/documentation/common/adding-script-references) topic to learn different approaches for adding script references in your Blazor application.
-## Add Syncfusion® Blazor File Upload component
+## Add Syncfusion® Blazor File Upload component
-Add the Syncfusion® Blazor File Upload component to a Razor page under the Pages folder (for example, Pages/Home.razor) in the **Server** or **Client** project. If the interactivity location is set to `Per page/component`, define a render mode at the top of the component as shown:
+The Syncfusion Blazor File Upload 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 `` tag to your `.razor` page. By default, this component provides a clean interface for users to select files locally.
| Interactivity location | RenderMode | Code |
| --- | --- | --- |
@@ -234,7 +238,7 @@ Add the Syncfusion® Blazor File Upload comp
| | WebAssembly | @rendermode InteractiveWebAssembly |
| | None | --- |
-N> If the **Interactivity Location** is set to `Global` and the **Render Mode** is `Auto` or `WebAssembly`, the render mode is configured in `App.razor` by default.
+N> If an **Interactivity Location** is set to `Global` and the **Render Mode** is set to `Auto` or `WebAssembly`, the render mode is configured in the `App.razor` file by default.
{% tabs %}
{% highlight razor %}
@@ -253,41 +257,60 @@ N> If the **Interactivity Location** is set to `Global` and the **Render Mode**
{% endhighlight %}
{% endtabs %}
-* Press Ctrl+F5 (Windows) or ⌘+F5 (macOS) to run the application. The Syncfusion® Blazor File Upload component should render in the browser.
+* 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.
+
+{% previewsample "https://blazorplayground.syncfusion.com/embed/LXBJXsrOqbMEOurR?appbar=false&editor=false&result=true&errorlist=false&theme=bootstrap5" %}
-{% previewsample "https://blazorplayground.syncfusion.com/embed/LXBJXsrOqbMEOurR?appbar=false&editor=false&result=true&errorlist=false&theme=bootstrap5" backgroundimage "[Blazor FileUpload Component](./images/blazor-fileupload-component.png)" %}
+
-## Without server-side API endpoint
+## Use ValueChange Event
-Upload files (and folder contents) without specifying a server-side API endpoint by using [AsyncSettings](https://help.syncfusion.com/cr/blazor/Syncfusion.Blazor.Inputs.UploaderAsyncSettings.html) and handling file streams in component events. This approach is suitable for local/demo scenarios. In production, validate file types and sizes, use unique file names, and store files in a secure, dedicated directory.
+The [`ValueChange`](https://help.syncfusion.com/cr/blazor/Syncfusion.Blazor.Inputs.UploaderEvents.html#Syncfusion_Blazor_Inputs_UploaderEvents_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.
-### Save and Remove actions
+### Code Example
-Access uploaded files as streams in the [ValueChange](https://help.syncfusion.com/cr/blazor/Syncfusion.Blazor.Inputs.UploaderEvents.html#Syncfusion_Blazor_Inputs_UploaderEvents_ValueChange) event and write them to the desired location. The following sample demonstrates the save action.
+This example demonstrates how to use the [`ValueChange`](https://help.syncfusion.com/cr/blazor/Syncfusion.Blazor.Inputs.UploaderEvents.html#Syncfusion_Blazor_Inputs_UploaderEvents_ValueChange) event to save uploaded files directly to a local directory when the [`AutoUpload`](https://help.syncfusion.com/cr/blazor/Syncfusion.Blazor.Inputs.SfUploader.html#Syncfusion_Blazor_Inputs_SfUploader_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.
{% tabs %}
{% highlight razor %}
@using Syncfusion.Blazor.Inputs
+@using System.IO
+
+
@code {
private async Task OnChange(UploadChangeEventArgs args)
{
try
{
- foreach (var file in args.Files)
+ foreach (var fileEntry 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();
+ // 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(ex.Message);
+ Console.WriteLine($"Error saving file: {ex.Message}");
}
}
}
@@ -295,20 +318,71 @@ Access uploaded files as streams in the [ValueChange](https://help.syncfusion.co
{% endhighlight %}
{% endtabs %}
-
+N> When saving files directly in a Blazor Server application using [`ValueChange`](https://help.syncfusion.com/cr/blazor/Syncfusion.Blazor.Inputs.UploaderEvents.html#Syncfusion_Blazor_Inputs_UploaderEvents_ValueChange) and [`AutoUpload`](https://help.syncfusion.com/cr/blazor/Syncfusion.Blazor.Inputs.SfUploader.html#Syncfusion_Blazor_Inputs_SfUploader_AutoUpload), 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/uploads` in this example) exists or is created programmatically. In a production environment, consider secure storage solutions for uploaded files.
+
+{% previewsample "https://blazorplayground.syncfusion.com/embed/hDVyZkrqBvaSlvht?appbar=false&editor=false&result=true&errorlist=false&theme=bootstrap5" %}
+
+
+
-When selecting the remove icon in the file list, the [OnRemove](https://help.syncfusion.com/cr/blazor/Syncfusion.Blazor.Inputs.UploaderEvents.html#Syncfusion_Blazor_Inputs_UploaderEvents_OnRemove) event provides the file name to remove. Implement logic in the OnRemove event to delete the corresponding file from the chosen storage location. The following sample illustrates the remove action pattern.
+## 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.
+
+### Code Example
+
+This example demonstrates how to read the content of an uploaded file into a [MemoryStream Class](https://learn.microsoft.com/en-us/dotnet/api/system.io.memorystream)`. 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.
{% tabs %}
-{% highlight cshtml %}
+{% highlight razor %}
+
+@using Syncfusion.Blazor.Inputs
+@using System.IO
-Private void onRemove(RemovingEventArgs args)
+
+
+
+
+@if (!string.IsNullOrEmpty(base64Image))
{
- foreach(var removeFile in args.FilesData)
+
Uploaded Image Preview (Base64)
+
+}
+
+@code {
+ private string base64Image;
+
+ private async Task OnValueChangeMemoryStream(UploadChangeEventArgs args)
{
- if (File.Exists(Path.Combine(@"rootPath", removeFile.Name)))
+ base64Image = string.Empty; // Clear previous image
+
+ foreach (var fileEntry in args.Files)
{
- File.Delete(Path.Combine(@"rootPath", removeFile.Name))
+ 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}");
+ }
}
}
}
@@ -316,109 +390,138 @@ Private void onRemove(RemovingEventArgs args)
{% endhighlight %}
{% endtabs %}
-## With server-side API endpoint
+N> When using `MemoryStream` for 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. The `long.MaxValue` in `OpenReadStream` indicates the maximum buffer size. In a Blazor Server app, `Stream` operations occur on the server.
+
+{% previewsample "https://blazorplayground.syncfusion.com/embed/BjreNaLUhdwxzvHS?appbar=false&editor=false&result=true&errorlist=false&theme=bootstrap5" %}
+
+
-The upload process requires save and remove action URL to manage the upload process in the server.
-N> * The save action is necessary to handle the upload operation.
- * The remove action is optional, one can handle the removed files from server.
+## Created Event
-N> * The save action is required to process uploaded files on the server.
- * The remove action is optional and is used to delete files from the server.
+The [`Created`](https://help.syncfusion.com/cr/blazor/Syncfusion.Blazor.Inputs.UploaderEvents.html#Syncfusion_Blazor_Inputs_UploaderEvents_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.
-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.
+### Code Example
-Specify the remove endpoint in the [RemoveUrl](https://help.syncfusion.com/cr/blazor/Syncfusion.Blazor.Inputs.UploaderAsyncSettings.html#Syncfusion_Blazor_Inputs_UploaderAsyncSettings_RemoveUrl) property. The [OnActionComplete](https://help.syncfusion.com/cr/blazor/Syncfusion.Blazor.Inputs.UploaderEvents.html#Syncfusion_Blazor_Inputs_UploaderEvents_OnActionComplete) event triggers after all selected files are processed (success or failure).
+This example shows how to use the [`Created`](https://help.syncfusion.com/cr/blazor/Syncfusion.Blazor.Inputs.UploaderEvents.html#Syncfusion_Blazor_Inputs_UploaderEvents_Created) event to add a custom message or dynamically change some aspect of the uploader's appearance right after it's created.
{% tabs %}
-{% highlight cshtml %}
+{% highlight razor %}
-[Route("api/[controller]")]
-public class SampleDataController : Controller
-{
- public string uploads = ".\\Uploaded Files"; // replace with your directory path
+@using Syncfusion.Blazor.Inputs
- [HttpPost("[action]")]
- public async Task Save(IFormFile UploadFiles) // Save the uploaded file here
- {
- if (UploadFiles.Length > 0)
- {
- //Create directory if not exists
- if (!Directory.Exists(uploads))
- {
- Directory.CreateDirectory(uploads);
- }
+
+
+
- var filePath = Path.Combine(uploads, UploadFiles.FileName);
- if (System.IO.File.Exists(filePath))
- {
- //Return conflict status code
- return new StatusCodeResult(StatusCodes.Status409Conflict);
- }
- using (var fileStream = new FileStream(filePath, FileMode.Create))
- {
- //Save the uploaded file to server
- await UploadFiles.CopyToAsync(fileStream);
- }
- }
- return Ok();
- }
+
@statusMessage
+@code {
+ private string statusMessage = "Uploader not yet created.";
- [HttpPost("[action]")]
- public void Remove(string UploadFiles) // Delete the uploaded file here
+ private void OnUploaderCreated()
{
- if(UploadFiles != null)
- {
- var filePath = Path.Combine(uploads, UploadFiles);
- if (System.IO.File.Exists(filePath))
- {
- //Delete the file from server
- System.IO.File.Delete(filePath);
- }
- }
+ 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");
}
}
{% endhighlight %}
{% endtabs %}
-The [OnFailure](https://help.syncfusion.com/cr/blazor/Syncfusion.Blazor.Inputs.UploaderEvents.html#Syncfusion_Blazor_Inputs_UploaderEvents_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.
+N> The [`Created`](https://help.syncfusion.com/cr/blazor/Syncfusion.Blazor.Inputs.UploaderEvents.html#Syncfusion_Blazor_Inputs_UploaderEvents_Created) event 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.
+
+{% previewsample "https://blazorplayground.syncfusion.com/embed/VtLyNuVUBGtPZrdo?appbar=false&editor=false&result=true&errorlist=false&theme=bootstrap5" %}
+
+
+
+
+## File Selected Event
+
+The [`FileSelected Event`](https://help.syncfusion.com/cr/blazor/Syncfusion.Blazor.Inputs.UploaderEvents.html#Syncfusion_Blazor_Inputs_UploaderEvents_FileSelected)event is triggered when files are chosen from the file explorer dialog, but **before** the [`ValueChange`](https://help.syncfusion.com/cr/blazor/Syncfusion.Blazor.Inputs.UploaderEvents.html#Syncfusion_Blazor_Inputs_UploaderEvents_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.
+
+### Code Example
+
+This example demonstrates how to use the [FileSelected Event](https://help.syncfusion.com/cr/blazor/Syncfusion.Blazor.Inputs.UploaderEvents.html#Syncfusion_Blazor_Inputs_UploaderEvents_FileSelected) event to prevent files larger than a certain size.
{% tabs %}
{% highlight razor %}
-
-
-
+@using Syncfusion.Blazor.Inputs
+@using System.Linq
+
+
+
+
@validationMessage
+
@code {
- private void OnFailureHandler(FailureEventArgs args)
- {
- // Here, you can customize your code.
- }
- private void OnActionCompleteHandler(ActionCompleteEventArgs args)
+ private string validationMessage = "";
+ private readonly long MaxFileSize = 1024 * 1024; // 1 MB
+
+ private void OnFileSelected(SelectedEventArgs args)
{
- // Here, you can customize your code.
+ 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.");
+ }
}
}
{% endhighlight %}
{% endtabs %}
-## Configure allowed file types
+N> Setting `args.Cancel = true` in the `FileSelected` event will prevent the file (or files if `args.Files` contains 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.
+
+{% previewsample "https://blazorplayground.syncfusion.com/embed/BDLIZuBUVwEJoJpz?appbar=false&editor=false&result=true&errorlist=false&theme=bootstrap5" %}
+
+
+
+
+## OnFileListRender
-Restrict uploads to specific file types using the [AllowedExtensions](https://help.syncfusion.com/cr/blazor/Syncfusion.Blazor.Inputs.UploaderModel.html#Syncfusion_Blazor_Inputs_UploaderModel_AllowedExtensions) property. Provide extensions as a comma-separated list. The Uploader filters selected or dropped files to match the specified types before uploading. For accurate client-side filtering, set the accept attribute on the underlying input element as needed.
+The [`OnFileListRender`](https://help.syncfusion.com/cr/blazor/Syncfusion.Blazor.Inputs.UploaderEvents.html#Syncfusion_Blazor_Inputs_UploaderEvents_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.
+
+### Code Example
+
+This example demonstrates how to use [`OnFileListRender`](https://help.syncfusion.com/cr/blazor/Syncfusion.Blazor.Inputs.UploaderEvents.html#Syncfusion_Blazor_Inputs_UploaderEvents_OnFileListRender)
{% tabs %}
{% highlight razor %}
-
+@using Syncfusion.Blazor.Inputs
+
+
+
+
+
+
+@code {
+ SfUploader fileobj;
+ private void OnFileListRenderHandler(FileListRenderingEventArgs args)
+ {
+
+ }
+}
{% endhighlight %}
{% endtabs %}
-{% previewsample "https://blazorplayground.syncfusion.com/embed/rXhzDsrOqbKVNviI?appbar=false&editor=false&result=true&errorlist=false&theme=bootstrap5" backgroundimage "[Allowing Specific Files in Blazor FileUpload](./images/blazor-fileupload-allow-specific-file.png)" %}
N> [View Sample in GitHub](https://github.com/SyncfusionExamples/Blazor-Getting-Started-Examples/tree/main/FileUpload).
@@ -427,4 +530,5 @@ N> [View Sample in GitHub](https://github.com/SyncfusionExamples/Blazor-Getting-
1. [Getting Started with Syncfusion® Blazor for client-side in .NET Core CLI](https://blazor.syncfusion.com/documentation/getting-started/blazor-webassembly-app)
2. [Getting Started with Syncfusion® Blazor for client-side in Visual Studio](https://blazor.syncfusion.com/documentation/getting-started/blazor-webassembly-visual-studio)
3. [Getting Started with Syncfusion® Blazor for server-side in .NET Core CLI](https://blazor.syncfusion.com/documentation/getting-started/blazor-web-app)
-4. [Getting Started with Syncfusion® File Upload in Blazor WebAssembly using Visual Studio](https://blazor.syncfusion.com/documentation/file-upload/how-to/getting-started-with-blazor-webassembly)
\ No newline at end of file
+4. [Getting Started with Syncfusion® File Upload in Blazor WebAssembly using Visual Studio](https://blazor.syncfusion.com/documentation/file-upload/how-to/getting-started-with-blazor-webassembly)
+5. [How to convert images to Base64 string with Blazor File Upload](https://support.syncfusion.com/kb/article/21178/how-to-convert-images-to-base64-string-with-blazor-file-upload)
\ No newline at end of file
diff --git a/blazor/file-upload/getting-started.md b/blazor/file-upload/getting-started.md
index f032a963d0..4b2ec2aca6 100644
--- a/blazor/file-upload/getting-started.md
+++ b/blazor/file-upload/getting-started.md
@@ -7,9 +7,9 @@ control: File Upload
documentation: ug
---
-# Getting Started with Blazor File Upload Component in WASM App
+# Getting Started with Blazor File Upload Component
-This guide explains how to add the [Blazor File Upload](https://www.syncfusion.com/blazor-components/blazor-file-upload) component to a Blazor WebAssembly (WASM) app using Visual Studio, Visual Studio Code, and the .NET CLI. It also outlines optional server API patterns that a WASM app can call for storing files.
+This section briefly explains how to include the [Blazor File Upload](https://www.syncfusion.com/blazor-components/blazor-file-upload) component in your Blazor WebAssembly App using Visual Studio, Visual Studio Code, and the .NET CLI.
{% tabcontents %}
@@ -17,15 +17,15 @@ This guide explains how to add the [Blazor File Upload](https://www.syncfusion.c
## Prerequisites
-* Review the [system requirements for Blazor components](https://blazor.syncfusion.com/documentation/system-requirements) and ensure the required .NET SDK and tooling are installed.
+* [System requirements for Blazor components](https://blazor.syncfusion.com/documentation/system-requirements)
## Create a new Blazor App in Visual Studio
-Create a **Blazor WebAssembly App** using Visual Studio via [Microsoft Templates](https://learn.microsoft.com/en-us/aspnet/core/blazor/tooling?view=aspnetcore-9.0&pivots=vs) or the [Syncfusion® Blazor Extension](https://blazor.syncfusion.com/documentation/visual-studio-integration/template-studio). For detailed instructions, refer to [this guide](https://blazor.syncfusion.com/documentation/getting-started/blazor-webassembly-app).
+You can create a **Blazor WebAssembly App** using Visual Studio via [Microsoft Templates](https://learn.microsoft.com/en-us/aspnet/core/blazor/tooling?view=aspnetcore-9.0&pivots=vs) or the [Syncfusion® Blazor Extension](https://blazor.syncfusion.com/documentation/visual-studio-integration/template-studio). For detailed instructions, refer to [this guide](https://blazor.syncfusion.com/documentation/getting-started/blazor-webassembly-app).
-## Install Syncfusion® Blazor Inputs and Themes NuGet in the App
+## Install Syncfusion® Blazor Inputs and Themes NuGet in the App
-To use the **Blazor File Upload** component, open NuGet Package Manager in Visual Studio (Tools → NuGet Package Manager → Manage NuGet Packages for Solution), then install [Syncfusion.Blazor.Inputs](https://www.nuget.org/packages/Syncfusion.Blazor.Inputs) and [Syncfusion.Blazor.Themes](https://www.nuget.org/packages/Syncfusion.Blazor.Themes/). Alternatively, use the following Package Manager commands.
+To add the **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](https://www.nuget.org/packages/Syncfusion.Blazor.Inputs) and [Syncfusion.Blazor.Themes](https://www.nuget.org/packages/Syncfusion.Blazor.Themes/). Alternatively, you can utilize the following package manager command to achieve the same.
{% tabs %}
{% highlight C# tabtitle="Package Manager" %}
@@ -36,7 +36,7 @@ Install-Package Syncfusion.Blazor.Themes -Version {{ site.releaseversion }}
{% endhighlight %}
{% endtabs %}
-N> Syncfusion® Blazor components are hosted on [nuget.org](https://www.nuget.org/packages?q=syncfusion.blazor). See the [NuGet packages](https://blazor.syncfusion.com/documentation/nuget-packages) topic for a complete package list and component details.
+N> Syncfusion® Blazor components are available in [nuget.org](https://www.nuget.org/packages?q=syncfusion.blazor). Refer to [NuGet packages](https://blazor.syncfusion.com/documentation/nuget-packages) topic for available NuGet packages list with component details.
{% endtabcontent %}
@@ -44,13 +44,13 @@ N> Syncfusion® Blazor components are hosted
## Prerequisites
-* Review the [system requirements for Blazor components](https://blazor.syncfusion.com/documentation/system-requirements) and install the latest .NET SDK.
+* [System requirements for Blazor components](https://blazor.syncfusion.com/documentation/system-requirements)
## Create a new Blazor App in Visual Studio Code
-Create a **Blazor WebAssembly App** using Visual Studio Code via [Microsoft Templates](https://learn.microsoft.com/en-us/aspnet/core/blazor/tooling?view=aspnetcore-7.0&pivots=vsc) or the [Syncfusion® Blazor Extension](https://blazor.syncfusion.com/documentation/visual-studio-code-integration/create-project). For step-by-step instructions, see [this guide](https://blazor.syncfusion.com/documentation/getting-started/blazor-webassembly-app?tabcontent=visual-studio-code).
+You can create a **Blazor WebAssembly App** using Visual Studio Code via [Microsoft Templates](https://learn.microsoft.com/en-us/aspnet/core/blazor/tooling?view=aspnetcore-7.0&pivots=vsc) or the [Syncfusion® Blazor Extension](https://blazor.syncfusion.com/documentation/visual-studio-code-integration/create-project). For detailed instructions, refer to [this guide](https://blazor.syncfusion.com/documentation/getting-started/blazor-webassembly-app?tabcontent=visual-studio-code).
-Alternatively, create a WebAssembly application using the following command in the terminal (Ctrl+`).
+Alternatively, you can create a WebAssembly application using the following command in the terminal(Ctrl+`).
{% tabs %}
@@ -63,11 +63,11 @@ cd BlazorApp
{% endtabs %}
-## Install Syncfusion® Blazor Inputs and Themes NuGet in the App
+## Install Syncfusion® Blazor Inputs and Themes NuGet in the App
-* Press Ctrl+` to open the integrated terminal in Visual Studio Code.
-* Ensure the project root directory where your `.csproj` file is located.
-* Run the following commands to install [Syncfusion.Blazor.Inputs](https://www.nuget.org/packages/Syncfusion.Blazor.Inputs) and [Syncfusion.Blazor.Themes](https://www.nuget.org/packages/Syncfusion.Blazor.Themes/) and restore dependencies.
+* Press Ctrl+` to open the integrated terminal in Visual Studio Code.
+* Ensure you’re in the project root directory where your `.csproj` file is located.
+* Run the following command to install a [Syncfusion.Blazor.Inputs](https://www.nuget.org/packages/Syncfusion.Blazor.Inputs) and [Syncfusion.Blazor.Themes](https://www.nuget.org/packages/Syncfusion.Blazor.Themes/) NuGet package and ensure all dependencies are installed.
{% tabs %}
@@ -81,7 +81,7 @@ dotnet restore
{% endtabs %}
-N> Syncfusion® Blazor components are hosted on [nuget.org](https://www.nuget.org/packages?q=syncfusion.blazor). See the [NuGet packages](https://blazor.syncfusion.com/documentation/nuget-packages) topic for a complete package list and component details.
+N> Syncfusion® Blazor components are available in [nuget.org](https://www.nuget.org/packages?q=syncfusion.blazor). Refer to [NuGet packages](https://blazor.syncfusion.com/documentation/nuget-packages) topic for available NuGet packages list with component details.
{% endtabcontent %}
@@ -89,7 +89,7 @@ N> Syncfusion® Blazor components are hosted
## Prerequisites
-Install the latest [.NET Core SDK](https://dotnet.microsoft.com/en-us/download). If already installed, check the version using the following command in a terminal or command prompt.
+Latest version of the [.NET Core SDK](https://dotnet.microsoft.com/en-us/download). If you previously installed the SDK, you can determine the installed version by executing the following command in a command prompt (Windows) or terminal (macOS) or command shell (Linux).
{% tabs %}
{% highlight c# tabtitle=".NET CLI" %}
@@ -99,9 +99,9 @@ dotnet --version
{% endhighlight %}
{% endtabs %}
-## Create a Blazor WebAssembly App using .NET CLI
+## Create a Blazor WebAssembly project using .NET CLI
-Run the `dotnet new blazorwasm` command to create a new Blazor WebAssembly app in a command prompt (Windows), terminal (macOS), or shell (Linux).
+Run the `dotnet new blazorwasm` command to create a new Blazor WebAssembly application in a command prompt (Windows) or terminal (macOS) or command shell (Linux).
{% tabs %}
{% highlight c# tabtitle=".NET CLI" %}
@@ -112,11 +112,11 @@ cd BlazorApp
{% endhighlight %}
{% endtabs %}
-This command creates a new Blazor WebAssembly app in a directory named `BlazorApp` at the current location. See the [Create Blazor app](https://dotnet.microsoft.com/en-us/learn/aspnet/blazor-tutorial/create) and [dotnet new CLI](https://learn.microsoft.com/en-us/dotnet/core/tools/dotnet-new) topics for details.
+This command creates new Blazor WebAssembly app project and places it in a new directory called `BlazorApp` inside your current location. See [Create Blazor app topic](https://dotnet.microsoft.com/en-us/learn/aspnet/blazor-tutorial/create) and [dotnet new CLI command](https://learn.microsoft.com/en-us/dotnet/core/tools/dotnet-new) topics for more details.
-## Install Syncfusion® Blazor Inputs and Themes NuGet in the App
+## Install Syncfusion® Blazor Inputs and Themes NuGet in the App
-Install the **Blazor File Upload** component packages using the .NET CLI. Run the following commands to install [Syncfusion.Blazor.Inputs](https://www.nuget.org/packages/Syncfusion.Blazor.Inputs/) and [Syncfusion.Blazor.Themes](https://www.nuget.org/packages/Syncfusion.Blazor.Themes/). See [Install and manage packages using the dotnet CLI](https://learn.microsoft.com/en-us/nuget/consume-packages/install-use-packages-dotnet-cli) for more information.
+Here's an example of how to add the **Blazor File Upload** component in the application using the following command in the command prompt (Windows) or terminal (Linux and macOS) to install a [Syncfusion.Blazor.Inputs](https://www.nuget.org/packages/Syncfusion.Blazor.Inputs/) and [Syncfusion.Blazor.Themes](https://www.nuget.org/packages/Syncfusion.Blazor.Themes/) NuGet package. See [Install and manage packages using the dotnet CLI](https://learn.microsoft.com/en-us/nuget/consume-packages/install-use-packages-dotnet-cli) topics for more details.
{% tabs %}
{% highlight c# tabtitle=".NET CLI" %}
@@ -128,7 +128,7 @@ dotnet restore
{% endhighlight %}
{% endtabs %}
-N> Syncfusion® Blazor components are hosted on [nuget.org](https://www.nuget.org/packages?q=syncfusion.blazor). See the [NuGet packages](https://blazor.syncfusion.com/documentation/nuget-packages) topic for a complete package list and component details.
+N> Syncfusion® Blazor components are available in [nuget.org](https://www.nuget.org/packages?q=syncfusion.blazor). Refer to [NuGet packages](https://blazor.syncfusion.com/documentation/nuget-packages) topic for available NuGet packages list with component details.
{% endtabcontent %}
@@ -136,7 +136,7 @@ N> Syncfusion® Blazor components are hosted
## Add Import Namespaces
-Open **~/_Imports.razor** and import the `Syncfusion.Blazor` and `Syncfusion.Blazor.Inputs` namespaces.
+Open the **~/_Imports.razor** file and import the `Syncfusion.Blazor` and `Syncfusion.Blazor.Inputs` namespace.
{% tabs %}
{% highlight razor tabtitle="~/_Imports.razor" %}
@@ -147,9 +147,9 @@ Open **~/_Imports.razor** and import the `Syncfusion.Blazor` and `Syncfusion.Bla
{% endhighlight %}
{% endtabs %}
-## Register Syncfusion® Blazor Service
+## Register Syncfusion® Blazor Service
-Register Syncfusion® Blazor services in **~/Program.cs** so the components are available to the app.
+Register the Syncfusion® Blazor Service in the **~/Program.cs** file of your Blazor WebAssembly App.
{% tabs %}
{% highlight C# tabtitle="~/Program.cs" hl_lines="3 11" %}
@@ -171,9 +171,9 @@ await builder.Build().RunAsync();
{% endhighlight %}
{% endtabs %}
-## Add stylesheet and script resources
+## Add Stylesheet and Script Resources
-The theme stylesheet and script are available via [Static Web Assets](https://blazor.syncfusion.com/documentation/appearance/themes#static-web-assets). Add the references in the `` section of **~/index.html**.
+The theme stylesheet and script can be accessed from NuGet through [Static Web Assets](https://blazor.syncfusion.com/documentation/appearance/themes#static-web-assets). Include the stylesheet and script references in the `` section of the **~/index.html** file.
```html
@@ -185,11 +185,24 @@ The theme stylesheet and script are available via [Static Web Assets](https://bl
```
-N> See the [Blazor Themes](https://blazor.syncfusion.com/documentation/appearance/themes) topic for ways to reference themes ([Static Web Assets](https://blazor.syncfusion.com/documentation/appearance/themes#static-web-assets), [CDN](https://blazor.syncfusion.com/documentation/appearance/themes#cdn-reference), and [CRG](https://blazor.syncfusion.com/documentation/common/custom-resource-generator)). For scripts, see [Adding Script Reference](https://blazor.syncfusion.com/documentation/common/adding-script-references). When using the consolidated Syncfusion script, separate per-component scripts are typically not required.
+N> Check out the [Blazor Themes](https://blazor.syncfusion.com/documentation/appearance/themes) topic to discover various methods ([Static Web Assets](https://blazor.syncfusion.com/documentation/appearance/themes#static-web-assets), [CDN](https://blazor.syncfusion.com/documentation/appearance/themes#cdn-reference), and [CRG](https://blazor.syncfusion.com/documentation/common/custom-resource-generator)) for referencing themes in your Blazor application. Also, check out the [Adding Script Reference](https://blazor.syncfusion.com/documentation/common/adding-script-references) topic to learn different approaches for adding script references in your Blazor application.
-## Add Blazor File Upload component
+## Add Syncfusion® Blazor File Upload component
-Add the Syncfusion® Blazor File Upload component in **~/Pages/Index.razor**.
+The Syncfusion Blazor File Upload 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 `` tag to your `.razor` page. By default, this component provides a clean interface for users to select files locally.
+
+Add the Syncfusion® Blazor File Upload component in the **~/Components/Pages/Home.razor** file. If an interactivity location as `per page/component`, define a render mode at the top of the `Home.razor` page.
+
+N> If an Interactivity Location is set to `Global` and the **Render Mode** is set to `Server`, the render mode is configured in the `App.razor` file by default.
+
+```
+@* desired render mode define here *@
+@rendermode InteractiveServer
+```
{% tabs %}
{% highlight razor %}
@@ -199,41 +212,60 @@ Add the Syncfusion® Blazor File Upload comp
{% endhighlight %}
{% endtabs %}
-* Press Ctrl+F5 (Windows) or ⌘+F5 (macOS) to run the application. The Syncfusion® Blazor File Upload component renders in the default browser.
+* 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.
+
+{% previewsample "https://blazorplayground.syncfusion.com/embed/LXBJXsrOqbMEOurR?appbar=false&editor=false&result=true&errorlist=false&theme=bootstrap5" %}
-{% previewsample "https://blazorplayground.syncfusion.com/embed/LXBJXsrOqbMEOurR?appbar=false&editor=false&result=true&errorlist=false&theme=bootstrap5" backgroundimage "[Blazor FileUpload Component](./images/blazor-fileupload-component.png)" %}
+
-## Without server-side API endpoint
+## Use ValueChange Event
-In a Blazor WebAssembly app, files can be selected and processed on the client without specifying a server-side API endpoint using [AsyncSettings](https://help.syncfusion.com/cr/blazor/Syncfusion.Blazor.Inputs.UploaderAsyncSettings.html). Client apps cannot write arbitrary files to the device file system. For persistence, use browser storage (such as IndexedDB) or upload to a server API.
+The [`ValueChange`](https://help.syncfusion.com/cr/blazor/Syncfusion.Blazor.Inputs.UploaderEvents.html#Syncfusion_Blazor_Inputs_UploaderEvents_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.
-### Save and Remove actions
+### Code Example
-The [ValueChange](https://help.syncfusion.com/cr/blazor/Syncfusion.Blazor.Inputs.UploaderEvents.html#Syncfusion_Blazor_Inputs_UploaderEvents_ValueChange) event exposes uploaded files as streams. The example below demonstrates a save handler pattern. In WebAssembly, adapt this logic to save to browser storage or to POST streams to a backend API. Avoid using unbounded stream limits in production.
+This example demonstrates how to use the [`ValueChange`](https://help.syncfusion.com/cr/blazor/Syncfusion.Blazor.Inputs.UploaderEvents.html#Syncfusion_Blazor_Inputs_UploaderEvents_ValueChange) event to save uploaded files directly to a local directory when the [`AutoUpload`](https://help.syncfusion.com/cr/blazor/Syncfusion.Blazor.Inputs.SfUploader.html#Syncfusion_Blazor_Inputs_SfUploader_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.
{% tabs %}
-{% highlight cshtml %}
+{% highlight razor %}
@using Syncfusion.Blazor.Inputs
+@using System.IO
+
+
@code {
private async Task OnChange(UploadChangeEventArgs args)
{
try
{
- foreach (var file in args.Files)
+ foreach (var fileEntry 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();
+ // 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(ex.Message);
+ Console.WriteLine($"Error saving file: {ex.Message}");
}
}
}
@@ -241,85 +273,70 @@ The [ValueChange](https://help.syncfusion.com/cr/blazor/Syncfusion.Blazor.Inputs
{% endhighlight %}
{% endtabs %}
-
+N> When saving files directly in a Blazor Server application using [`ValueChange`](https://help.syncfusion.com/cr/blazor/Syncfusion.Blazor.Inputs.UploaderEvents.html#Syncfusion_Blazor_Inputs_UploaderEvents_ValueChange) and [`AutoUpload`](https://help.syncfusion.com/cr/blazor/Syncfusion.Blazor.Inputs.SfUploader.html#Syncfusion_Blazor_Inputs_SfUploader_AutoUpload), 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/uploads` in this example) exists or is created programmatically. In a production environment, consider secure storage solutions for uploaded files.
-When the remove icon is selected in the file list, the [OnRemove](https://help.syncfusion.com/cr/blazor/Syncfusion.Blazor.Inputs.UploaderEvents.html#Syncfusion_Blazor_Inputs_UploaderEvents_OnRemove) event provides the file name to remove. Implement the remove logic appropriate to your storage choice (for example, removing from IndexedDB or calling a backend API). The following sample shows the event signature pattern.
+{% previewsample "https://blazorplayground.syncfusion.com/embed/hDVyZkrqBvaSlvht?appbar=false&editor=false&result=true&errorlist=false&theme=bootstrap5" %}
-{% tabs %}
-{% highlight cshtml %}
+
-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))
- }
- }
-}
-{% endhighlight %}
-{% endtabs %}
+## Memory stream
-## With server-side API endpoint
+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.
-The upload process requires save and remove action URL to manage the upload process in the server.
+### Code Example
-N> * The save action is necessary to handle the upload operation.
- * The remove action is optional, one can handle the removed files from server.
+This example demonstrates how to read the content of an uploaded file into a [MemoryStream Class](https://learn.microsoft.com/en-us/dotnet/api/system.io.memorystream)`. 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.
-The save action handler upload the files that needs to be specified in the [SaveUrl](https://help.syncfusion.com/cr/blazor/Syncfusion.Blazor.Inputs.UploaderAsyncSettings.html#Syncfusion_Blazor_Inputs_UploaderAsyncSettings_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.
+{% tabs %}
+{% highlight razor %}
-Set the [RemoveUrl](https://help.syncfusion.com/cr/blazor/Syncfusion.Blazor.Inputs.UploaderAsyncSettings.html#Syncfusion_Blazor_Inputs_UploaderAsyncSettings_RemoveUrl) property to the server endpoint that deletes files. The [OnActionComplete](https://help.syncfusion.com/cr/blazor/Syncfusion.Blazor.Inputs.UploaderEvents.html#Syncfusion_Blazor_Inputs_UploaderEvents_OnActionComplete) event triggers after all selected files are processed (success or failure).
+@using Syncfusion.Blazor.Inputs
+@using System.IO
-{% tabs %}
-{% highlight cshtml %}
+
+
+
-[Route("api/[controller]")]
-public class SampleDataController : Controller
+@if (!string.IsNullOrEmpty(base64Image))
{
- public string uploads = ".\\Uploaded Files"; // replace with your directory path
+
Uploaded Image Preview (Base64)
+
+}
+
+@code {
+ private string base64Image;
- [HttpPost("[action]")]
- public async Task Save(IFormFile UploadFiles) // Save the uploaded file here
+ private async Task OnValueChangeMemoryStream(UploadChangeEventArgs args)
{
- if (UploadFiles.Length > 0)
- {
- //Create directory if not exists
- if (!Directory.Exists(uploads))
- {
- Directory.CreateDirectory(uploads);
- }
+ base64Image = string.Empty; // Clear previous image
- var filePath = Path.Combine(uploads, UploadFiles.FileName);
- if (System.IO.File.Exists(filePath))
- {
- //Return conflict status code
- return new StatusCodeResult(StatusCodes.Status409Conflict);
- }
- using (var fileStream = new FileStream(filePath, FileMode.Create))
+ foreach (var fileEntry in args.Files)
+ {
+ if (fileEntry.FileInfo.Type.StartsWith("image/", StringComparison.OrdinalIgnoreCase))
{
- //Save the uploaded file to server
- await UploadFiles.CopyToAsync(fileStream);
+ // 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.");
}
- }
- return Ok();
- }
-
-
- [HttpPost("[action]")]
- public void Remove(string UploadFiles) // Delete the uploaded file here
- {
- if(UploadFiles != null)
- {
- var filePath = Path.Combine(uploads, UploadFiles);
- if (System.IO.File.Exists(filePath))
+ else
{
- //Delete the file from server
- System.IO.File.Delete(filePath);
+ 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}");
}
}
}
@@ -328,181 +345,146 @@ public class SampleDataController : Controller
{% endhighlight %}
{% endtabs %}
-The [OnFailure](https://help.syncfusion.com/cr/blazor/Syncfusion.Blazor.Inputs.UploaderEvents.html#Syncfusion_Blazor_Inputs_UploaderEvents_OnFailure) event is raised when an AJAX request fails during upload or removal. Use it to surface and handle server-side errors in the UI.
+N> When using `MemoryStream` for 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. The `long.MaxValue` in `OpenReadStream` indicates the maximum buffer size. In a Blazor Server app, `Stream` operations occur on the server.
-{% tabs %}
-{% highlight razor %}
+{% previewsample "https://blazorplayground.syncfusion.com/embed/BjreNaLUhdwxzvHS?appbar=false&editor=false&result=true&errorlist=false&theme=bootstrap5" %}
-
-
-
-
-@code {
- private void OnFailureHandler(FailureEventArgs args)
- {
- // Here, you can customize your code.
- }
- private void OnActionCompleteHandler(ActionCompleteEventArgs args)
- {
- // Here, you can customize your code.
- }
-}
+
-{% endhighlight %}
-{% endtabs %}
-
-### Server-side configuration for saving and returning responses
-The following sample demonstrates a server action that saves files and returns responses in JSON, string, and file formats. In production, validate file type and size, sanitize file names, use unique file naming, and write to a dedicated uploads directory.
+## Created Event
-{% tabs %}
-{% highlight cshtml %}
+The [`Created`](https://help.syncfusion.com/cr/blazor/Syncfusion.Blazor.Inputs.UploaderEvents.html#Syncfusion_Blazor_Inputs_UploaderEvents_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.
-[Route("api/[controller]")]
+### Code Example
-private IHostingEnvironment hostingEnv;
+This example shows how to use the [`Created`](https://help.syncfusion.com/cr/blazor/Syncfusion.Blazor.Inputs.UploaderEvents.html#Syncfusion_Blazor_Inputs_UploaderEvents_Created) event to add a custom message or dynamically change some aspect of the uploader's appearance right after it's created.
-public SampleDataController(IHostingEnvironment env)
-{
- this.hostingEnv = env;
-}
-
-[HttpPost("[action]")]
-public IActionResult Save()
-{
- // for JSON Data
- try
- {
- // Process uploaded files
- var responseData = new
- {
- Success = true,
- Message = "Files uploaded successfully",
- // Additional data can be added here
- };
+{% tabs %}
+{% highlight razor %}
- return Ok(responseData);
- }
- catch (Exception e)
- {
- var errorResponse = new
- {
- Success = false,
- Message = "File upload failed: " + e.Message
- };
+@using Syncfusion.Blazor.Inputs
- return BadRequest(errorResponse);
- }
+
+
+
- // for String Data
- try
- {
- // Process string data
- var data = "success";
- // Return the string data
- return Content(data);
- }
- catch (Exception)
- {
- var data = "failed";
- return Content(data);
- }
+
@statusMessage
- // for File Data
- try
- {
- // Example: Retrieve file path for stream.txt
- var filePath = "stream.txt"; // Example file path
-
- var fullPath = Path.GetFullPath(filePath);
+@code {
+ private string statusMessage = "Uploader not yet created.";
- // Return the file
- return PhysicalFile(fullPath, "text/plain");
- }
- catch (Exception e)
+ private void OnUploaderCreated()
{
- return Content("Failed to retrieve file response: " + e.Message, "text/plain");
+ 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");
}
-
}
{% endhighlight %}
{% endtabs %}
-### Client-side configuration for saving and returning responses
+N> The [`Created`](https://help.syncfusion.com/cr/blazor/Syncfusion.Blazor.Inputs.UploaderEvents.html#Syncfusion_Blazor_Inputs_UploaderEvents_Created) event 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.
-The following sample shows how to handle success responses on the client and interpret JSON/string/file responses from the server. Adapt the logic to your API contract.
+{% previewsample "https://blazorplayground.syncfusion.com/embed/VtLyNuVUBGtPZrdo?appbar=false&editor=false&result=true&errorlist=false&theme=bootstrap5" %}
+
+
+
+
+## File Selected Event
+
+The [`FileSelected Event`](https://help.syncfusion.com/cr/blazor/Syncfusion.Blazor.Inputs.UploaderEvents.html#Syncfusion_Blazor_Inputs_UploaderEvents_FileSelected)event is triggered when files are chosen from the file explorer dialog, but **before** the [`ValueChange`](https://help.syncfusion.com/cr/blazor/Syncfusion.Blazor.Inputs.UploaderEvents.html#Syncfusion_Blazor_Inputs_UploaderEvents_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.
+
+### Code Example
+
+This example demonstrates how to use the [FileSelected Event](https://help.syncfusion.com/cr/blazor/Syncfusion.Blazor.Inputs.UploaderEvents.html#Syncfusion_Blazor_Inputs_UploaderEvents_FileSelected) event to prevent files larger than a certain size.
{% tabs %}
-{% highlight cshtml %}
+{% highlight razor %}
@using Syncfusion.Blazor.Inputs
-@using System.Text.Json
+@using System.Linq
-
-
-
-
+
+
+
@validationMessage
@code {
+ private string validationMessage = "";
+ private readonly long MaxFileSize = 1024 * 1024; // 1 MB
- private void OnSuccessHandler(SuccessEventArgs args)
+ private void OnFileSelected(SelectedEventArgs args)
{
- if (args.Response is not null) // Check if the event argument is not null
+ validationMessage = "";
+ foreach (var file in args.FilesData)
{
- var responseText = args.Response.ResponseText;
- if (!string.IsNullOrWhiteSpace(responseText))
- {
- // for JSON and File Datas
- using var jsonDoc = JsonDocument.Parse(responseText);
- var jsonResponse = jsonDoc.RootElement;
-
- if (jsonResponse.TryGetProperty("success", out var successProp))
- {
- var isSuccess = successProp.GetBoolean();
-
- if (isSuccess)
- {
- // File upload success
- var message = jsonResponse.TryGetProperty("message", out var messageProp) ? messageProp.GetString() : "File uploaded successfully";
-
- // Additional processing as needed
- }
- }
-
-
- // for string Data
- var message = responseText;
- // Additional processing as needed
- }
+ 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.");
}
}
-
}
{% endhighlight %}
{% endtabs %}
-## Configure allowed file types
+N> Setting `args.Cancel = true` in the `FileSelected` event will prevent the file (or files if `args.Files` contains 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.
-Restrict uploads to specific file types using the [AllowedExtensions](https://help.syncfusion.com/cr/blazor/Syncfusion.Blazor.Inputs.UploaderModel.html#Syncfusion_Blazor_Inputs_UploaderModel_AllowedExtensions) property. Provide extensions as a comma-separated list, typically with a leading dot for each extension. The Uploader filters selected or dropped files to match the specified types and then processes the upload operation. For client-side filtering, ensure the accept attribute of the underlying input reflects the same extensions.
+{% previewsample "https://blazorplayground.syncfusion.com/embed/BDLIZuBUVwEJoJpz?appbar=false&editor=false&result=true&errorlist=false&theme=bootstrap5" %}
+
+
+
+
+## OnFileListRender
+
+The [`OnFileListRender`](https://help.syncfusion.com/cr/blazor/Syncfusion.Blazor.Inputs.UploaderEvents.html#Syncfusion_Blazor_Inputs_UploaderEvents_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.
+
+### Code Example
+
+This example demonstrates how to use [`OnFileListRender`](https://help.syncfusion.com/cr/blazor/Syncfusion.Blazor.Inputs.UploaderEvents.html#Syncfusion_Blazor_Inputs_UploaderEvents_OnFileListRender)
{% tabs %}
{% highlight razor %}
-
+@using Syncfusion.Blazor.Inputs
+
+
+
+
+
+
+@code {
+ SfUploader fileobj;
+ private void OnFileListRenderHandler(FileListRenderingEventArgs args)
+ {
+
+ }
+}
{% endhighlight %}
{% endtabs %}
-{% previewsample "https://blazorplayground.syncfusion.com/embed/rXhzDsrOqbKVNviI?appbar=false&editor=false&result=true&errorlist=false&theme=bootstrap5" backgroundimage "[Allowing Specific Files in Blazor FileUpload](./images/blazor-fileupload-allow-specific-file.png)" %}
N> [View Sample in GitHub](https://github.com/SyncfusionExamples/Blazor-Getting-Started-Examples/tree/main/FileUpload).
+
## See also
* [Getting Started with Syncfusion® Blazor for Client-Side in .NET Core CLI](https://blazor.syncfusion.com/documentation/getting-started/blazor-webassembly-app)
* [Getting Started with Syncfusion® Blazor for Server-side in Visual Studio](https://blazor.syncfusion.com/documentation/getting-started/blazor-server-side-visual-studio)
* [Getting Started with Syncfusion® Blazor for Server-Side in .NET Core CLI](https://blazor.syncfusion.com/documentation/getting-started/blazor-web-app)
-* [Getting Started with Syncfusion® File Upload in Blazor WebAssembly using Visual Studio](https://blazor.syncfusion.com/documentation/file-upload/how-to/getting-started-with-blazor-webassembly)
\ No newline at end of file
+* [Getting Started with Syncfusion® File Upload in Blazor WebAssembly using Visual Studio](https://blazor.syncfusion.com/documentation/file-upload/how-to/getting-started-with-blazor-webassembly)
+* [How to convert images to Base64 string with Blazor File Upload](https://support.syncfusion.com/kb/article/21178/how-to-convert-images-to-base64-string-with-blazor-file-upload)
diff --git a/blazor/file-upload/images/blazor-fileupload-basic.gif b/blazor/file-upload/images/blazor-fileupload-basic.gif
new file mode 100644
index 0000000000..68ffe86d17
Binary files /dev/null and b/blazor/file-upload/images/blazor-fileupload-basic.gif differ
diff --git a/blazor/file-upload/images/blazor-fileupload-created.gif b/blazor/file-upload/images/blazor-fileupload-created.gif
new file mode 100644
index 0000000000..11759f373a
Binary files /dev/null and b/blazor/file-upload/images/blazor-fileupload-created.gif differ
diff --git a/blazor/file-upload/images/blazor-fileupload-fileselected.gif b/blazor/file-upload/images/blazor-fileupload-fileselected.gif
new file mode 100644
index 0000000000..8617f4b867
Binary files /dev/null and b/blazor/file-upload/images/blazor-fileupload-fileselected.gif differ
diff --git a/blazor/file-upload/images/blazor-fileupload-memorystream.gif b/blazor/file-upload/images/blazor-fileupload-memorystream.gif
new file mode 100644
index 0000000000..f2146ef200
Binary files /dev/null and b/blazor/file-upload/images/blazor-fileupload-memorystream.gif differ
diff --git a/blazor/file-upload/images/blazor-fileupload-valuechange.gif b/blazor/file-upload/images/blazor-fileupload-valuechange.gif
new file mode 100644
index 0000000000..afd16653d8
Binary files /dev/null and b/blazor/file-upload/images/blazor-fileupload-valuechange.gif differ