How to upload Files to Server with the Blazor File upload component?
This article explains how to upload files to the server using the Syncfusion Blazor File Upload component, which provides extensive options for file upload operations.
Getting Started
To render the Syncfusion Blazor File Upload component, please follow the steps in the getting started documentation.
Upload Methods
The Blazor File Upload component offers multiple methods for uploading files to a server in your Blazor application:
- Without server-side API endpoint
- With server-side API endpoint (Async Settings)
Without Server-Side API Endpoint
In this approach, you can get the uploaded files as a file stream in the ValueChange
event argument. You can then implement a save handler within this event to save the files to your desired location.
Here’s a step-by-step implementation:
- Set
AutoUpload
tofalse
to disable automatic uploading - Handle the
ValueChange
event to capture uploaded files - Save the files to the desired location using FileStream
@using Syncfusion.Blazor.Inputs
@using System.IO
<SfUploader ID="UploadFiles" AutoUpload="false">
<UploaderEvents ValueChange="OnChange"></UploaderEvents>
</SfUploader>
@code {
public void OnChange(UploadChangeEventArgs args)
{
foreach (var file in args.Files)
{
var path = @"path" + file.FileInfo.Name;
FileStream filestream = new FileStream(path, FileMode.Create, FileAccess.Write);
file.Stream.WriteTo(filestream);
filestream.Close();
file.Stream.Close();
}
}
}
With Server-Side API Endpoint (Async Settings)
The File Upload component supports asynchronous file uploads, which requires configuring save and remove action URLs to manage the upload process on the server:
- Save action (required): Handles the upload operation and must be specified in the
SaveUrl
property - Remove action (optional): Handles file removal from the server and is specified in the
RemoveUrl
property
Using Pre-Hosted Server Endpoints
You can use pre-hosted server endpoints for the save and remove actions as shown below:
@using Syncfusion.Blazor.Inputs
<SfUploader ID="UploadFiles">
<UploaderAsyncSettings SaveUrl="https://aspnetmvc.syncfusion.com/services/api/uploadbox/Save"
RemoveUrl="https://aspnetmvc.syncfusion.com/services/api/uploadbox/Remove">
</UploaderAsyncSettings>
</SfUploader>
Configuring Custom Endpoints in Your Application
Alternatively, you can configure custom save and remove handlers in your application:
@using Syncfusion.Blazor.Inputs
<SfUploader ID="UploadFiles">
<UploaderAsyncSettings SaveUrl="api/SampleData/Save"
RemoveUrl="api/SampleData/Remove">
</UploaderAsyncSettings>
</SfUploader>
Implementing Controller Methods for File Upload
For this approach, you need to create an API controller and implement the save and remove actions. Here’s a implementation that handles both regular uploads and chunked uploads for large files:
// SampleDataController.cs
public string uploads = Path.Combine(Directory.GetCurrentDirectory(), "Uploaded Files"); // Set your desired upload directory path
public async Task<IActionResult> Save(IFormFile UploadFiles)
{
try
{
if (UploadFiles.Length > 0)
{
var fileName = UploadFiles.FileName;
// Create upload directory if it doesn't exist
if (!Directory.Exists(uploads))
{
Directory.CreateDirectory(uploads);
}
if (UploadFiles.ContentType == "application/octet-stream") //Handle chunk upload
{
// Fetch chunk-index and total-chunk from form data
var chunkIndex = Request.Form["chunk-index"];
var totalChunk = Request.Form["total-chunk"];
// Path to save the chunk files with .part extension
var tempFilePath = Path.Combine(uploads, fileName + ".part");
using (var fileStream = new FileStream(tempFilePath, chunkIndex == "0" ? FileMode.Create : FileMode.Append))
{
await UploadFiles.CopyToAsync(fileStream);
}
// If all chunks are uploaded, move the file to the final destination
if (Convert.ToInt32(chunkIndex) == Convert.ToInt32(totalChunk) - 1)
{
var finalFilePath = Path.Combine(uploads, fileName);
// Move the .part file to the final destination without the .part extension
System.IO.File.Move(tempFilePath, finalFilePath);
return Ok(new { status = "File uploaded successfully" });
}
return Ok(new { status = "Chunk uploaded successfully" });
}
else //Handle normal upload
{
var filePath = Path.Combine(uploads, fileName);
using (var fileStream = new FileStream(filePath, FileMode.Create))
{
await UploadFiles.CopyToAsync(fileStream);
}
return Ok(new { status = "File uploaded successfully" });
}
}
return BadRequest(new { status = "No file to upload" });
}
catch (Exception ex)
{
return StatusCode(500, new { status = "Error", message = ex.Message });
}
}
// Method to handle file removal
public async Task<IActionResult> Remove(string UploadFiles)
{
try
{
var filePath = Path.Combine(uploads, UploadFiles);
if (System.IO.File.Exists(filePath))
{
System.IO.File.Delete(filePath);
return Ok(new { status = "File deleted successfully" });
}
else
{
return NotFound(new { status = "File not found" });
}
}
catch (Exception ex)
{
return StatusCode(500, new { status = "Error", message = ex.Message });
}
}
This implementation provides:
- Support for both regular file uploads and chunked uploads for large files
- Proper error handling with appropriate HTTP status codes
- File cleanup functionality for removing files when needed
To enable chunked upload in your Blazor File Upload component, configure the ChunkSize
property in the UploaderAsyncSettings
:
<SfUploader ID="UploadFiles">
<UploaderAsyncSettings SaveUrl="api/SampleData/Save"
RemoveUrl="api/SampleData/Remove"
ChunkSize="500000">
</UploaderAsyncSettings>
</SfUploader>
Additional Resources
For more information about the File Upload component, refer to these resources:
Conclusion
We hope you found this guide helpful for implementing file uploads in your Blazor application using the Syncfusion File Upload component. For a comprehensive overview of all features, please visit our Blazor File Upload feature tour page.
For current customers, our Blazor components are available on the License and Downloads page. If you’re new to Syncfusion, you can try our 30-day free trial to evaluate our Blazor File Upload and other Blazor components.
If you have any questions or need clarification, please let us know in the comments section below. You can also contact us through our support forums, Direct-Trac, or feedback portal. We’re always happy to assist you!