How to upload Files to Server with the Blazor File upload component?
This article explains how to upload files to the server with the Syncfusion Blazor File Upload component.
To render the Syncfusion component, please follow the steps given in the getting started documentation.
You can upload files from a folder to the server using the following methods in a Blazor application:
- Without server-side API endpoint
- With server-side API endpoint (Async Settings)
Without server-side API endpoint
Please refer to the following code example:
@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(); } } }
Also, you can download and run the sample from this link.
With server-side API endpoint
The Uploader component allows you to upload files asynchronously. The upload process requires save and remove action URL to manage the upload process in the server.
- The save action is necessary to handle the upload operation.
- The remove action is optional; it allows you to handle the removed files from the server.
The save action handler upload the files that needs to be specified in the SaveUrl property. The save handler receives the submitted files and manages the save process in the server.
The remove action is optional. The remove action handler removes the files that needs to be specified in the RemoveUrl property.
The save and remove URLs can be pre-hosted on the server for the Uploader component as mentioned in the following code example. Alternatively, you can configure the save and remove handlers in the application itself.
Here, the save and remove URL provided as pre-hosted server link.
@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>
Here, the save and remove handler configured in the SampleDataController.cs file.
@using Syncfusion.Blazor.Inputs <SfUploader ID="UploadFiles"> <UploaderAsyncSettings SaveUrl="api/SampleData/Save" RemoveUrl="api/SampleData/Remove"></UploaderAsyncSettings> </SfUploader>
For this, you need to create the API controller named “SampleDataController” under the Data directory and configure the below actions in the controller to perform save and remove action.
[Data/SampleDataController.cs]
private IHostingEnvironment hostingEnv; public SampleDataController(IHostingEnvironment env) { this.hostingEnv = env; } // Save handler [HttpPost("[action]")] public void Save(IList<IFormFile> chunkFile, IList<IFormFile> UploadFiles) { long size = 0; try { foreach (var file in UploadFiles) { var filename = ContentDispositionHeaderValue .Parse(file.ContentDisposition) .FileName .Trim('"'); var folders = filename.Split('/'); var uploaderFilePath = hostingEnv.ContentRootPath; // for Directory upload if (folders.Length > 1) { for (var i = 0; i < folders.Length - 1; i++) { var newFolder = uploaderFilePath + $@"\{folders[i]}"; Directory.CreateDirectory(newFolder); uploaderFilePath = newFolder; filename = folders[i + 1]; } } filename = uploaderFilePath + $@"\{filename}"; size += file.Length; if (!System.IO.File.Exists(filename)) { using (FileStream fs = System.IO.File.Create(filename)) { file.CopyTo(fs); fs.Flush(); } } } } catch (Exception e) { Response.Clear(); Response.StatusCode = 204; Response.HttpContext.Features.Get<IHttpResponseFeature>().ReasonPhrase = "File failed to upload"; Response.HttpContext.Features.Get<IHttpResponseFeature>().ReasonPhrase = e.Message; } } // Remove handler [HttpPost("[action]")] public void Remove(IList<IFormFile> UploadFiles) { try { var filename = hostingEnv.ContentRootPath + $@"\{UploadFiles[0].FileName}"; if (System.IO.File.Exists(filename)) { System.IO.File.Delete(filename); } } catch (Exception e) { Response.Clear(); Response.StatusCode = 200; Response.HttpContext.Features.Get<IHttpResponseFeature>().ReasonPhrase = "File removed successfully"; Response.HttpContext.Features.Get<IHttpResponseFeature>().ReasonPhrase = e.Message; } }
To upload a file to the server in a server-side Blazor application, you need to configure UseMvcWithDefaultRoute in ASP.NET Core 3.0 and add services.AddMvc(option => option.EnableEndpointRouting = false).SetCompatibilityVersion(CompatibilityVersion.Version_3_0) to IServiceCollection which requires an explicit opt-in inside the Startup.cs page.
public void ConfigureServices(IServiceCollection services) { services.AddMvc(option => option.EnableEndpointRouting = false).SetCompatibilityVersion(CompatibilityVersion.Version_3_0); services.AddRazorPages(); services.AddServerSideBlazor(); services.AddSyncfusionBlazor(); services.AddSingleton<WeatherForecastService>(); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { app.UseExceptionHandler("/Error"); // The default HSTS value is 30 days. You may change the HSTS value for the production scenarios, see https://aka.ms/aspnetcore-hsts. app.UseHsts(); } app.UseHttpsRedirection(); app.UseStaticFiles(); app.UseMvcWithDefaultRoute(); app.UseRouting(); app.UseEndpoints(endpoints => { endpoints.MapBlazorHub(); endpoints.MapFallbackToPage("/_Host"); }); }
You can download and run the sample from this link.
To learn more about the Uploader component, refer to this Documentation, API Reference, and Demo sites.
We hope you enjoyed learning about how to upload files to a server with the Blazor File Upload component.
You can refer to our Blazor File Upload feature tour page to know about its other groundbreaking features, documentation, and how to quickly get started with configuration specifications.
For current customers, our Blazor components are available on the License and Downloads page. If you are 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 require clarifications, please let us know in the comments section below. You can also contact us through our support forums, Direct-Trac, or feedback portal. We are always happy to assist you!