Skip to content

Commit 7f0cb4f

Browse files
authored
983306: Re-structing the form integration section of File uploader.
1 parent 358ca45 commit 7f0cb4f

File tree

4 files changed

+209
-0
lines changed

4 files changed

+209
-0
lines changed

blazor-toc.html

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2914,6 +2914,7 @@
29142914
<li> <a href="/blazor/file-upload/template">Template</a></li>
29152915
<li> <a href="/blazor/file-upload/validation">Validation</a></li>
29162916
<li> <a href="/blazor/file-upload/style-appearance">Style and Appearance</a></li>
2917+
<li> <a href="/blazor/file-upload/form-integration.md">Form Integration</a></li>
29172918
<li> <a href="/blazor/file-upload/http-client">Http Client</a></li>
29182919
<li>How To
29192920
<ul>
Lines changed: 208 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,208 @@
1+
---
2+
layout: post
3+
title: Form Integration in Blazor File Upload Component | Syncfusion
4+
description: Learn how to integrate the Syncfusion Blazor File Upload component with Blazor's EditForm and DataForm for seamless form-based file management.
5+
platform: Blazor
6+
control: File Upload
7+
documentation: ug
8+
---
9+
10+
# Form Integration in Blazor File Upload Component
11+
12+
The Syncfusion Blazor File Upload component can be integrated with Blazor's `EditForm` and `DataForm` to build robust forms that include file-handling capabilities. This allows you to associate file uploads with a model and trigger validation.
13+
14+
In a form, file validation is triggered by populating a model property when a file is selected and clearing it when removed. The `FileSelected` and `OnRemove` events are used for this purpose. When the form is submitted, the file can be uploaded manually to a server-side endpoint.
15+
16+
## File Upload with EditForm Integration
17+
18+
The File Upload component can be integrated into a Blazor `EditForm` to manage file uploads as part of your data entry process.
19+
20+
To validate the file input, a model property is updated using the `FileSelected` and `OnRemove` events. The file upload is initiated only when the form is valid by calling the `UploadAsync` method in the `OnValidSubmit` event handler.
21+
22+
### Uploading to a Server-Side API (Blazor WASM and Server)
23+
24+
This example shows how to configure the File Upload component to send files to a server-side API endpoint upon form submission. This approach is compatible with both Blazor WebAssembly and Blazor Server applications.
25+
26+
```cshtml
27+
@using System.ComponentModel.DataAnnotations
28+
@using Syncfusion.Blazor.Inputs
29+
30+
<EditForm Model="@employee" OnValidSubmit="@HandleValidSubmit">
31+
<DataAnnotationsValidator />
32+
<div class="form-group">
33+
<SfUploader @ref="UploadObj" AllowMultiple="false" AutoUpload="false" ID="UploadFiles">
34+
<UploaderAsyncSettings SaveUrl="https://blazor.syncfusion.com/services/production/api/FileUploader/Save"
35+
RemoveUrl="https://blazor.syncfusion.com/services/production/api/FileUploader/Remove"></UploaderAsyncSettings>
36+
<UploaderEvents OnRemove="OnRemove" FileSelected="OnSelect"></UploaderEvents>
37+
</SfUploader>
38+
<ValidationMessage For="() => employee.files" />
39+
</div>
40+
<button type="submit" class="btn btn-primary">Submit</button>
41+
</EditForm>
42+
43+
@code {
44+
private SfUploader UploadObj;
45+
46+
public class Employee
47+
{
48+
[Required(ErrorMessage = "Please upload a file")]
49+
public List<UploaderUploadedFiles> files { get; set; }
50+
}
51+
52+
public Employee employee = new Employee();
53+
54+
public void OnSelect(SelectedEventArgs args)
55+
{
56+
this.employee.files = new List<UploaderUploadedFiles> { new UploaderUploadedFiles { Name = args.FilesData[0].Name, Type = args.FilesData[0].Type, Size = args.FilesData[0].Size } };
57+
}
58+
59+
public void OnRemove()
60+
{
61+
this.employee.files = null;
62+
}
63+
64+
public async Task HandleValidSubmit()
65+
{
66+
// Upload the selected file manually only when the form is valid
67+
await this.UploadObj.UploadAsync();
68+
}
69+
}
70+
```
71+
72+
### Saving Files Directly to the File System (Blazor Server Only)
73+
74+
In a Blazor Server application, you can save uploaded files directly to the server's file system. The following example demonstrates how to use the `ValueChange` event to read the file stream and save it to a path.
75+
76+
> This method writes files to the server's local file system and is only supported in Blazor Server applications. It will not work in a Blazor WebAssembly environment.
77+
78+
```cshtml
79+
@using System.ComponentModel.DataAnnotations
80+
@using Syncfusion.Blazor.Inputs
81+
82+
<EditForm Model="@employee" OnValidSubmit="@HandleValidSubmit">
83+
<DataAnnotationsValidator />
84+
<div class="form-group">
85+
<SfUploader @ref="UploadObj" AllowMultiple="false" AutoUpload="false" ID="UploadFiles">
86+
<UploaderEvents ValueChange="OnChange" OnRemove="OnRemove" FileSelected="OnSelect"></UploaderEvents>
87+
</SfUploader>
88+
<ValidationMessage For="() => employee.files" />
89+
</div>
90+
<button type="submit" class="btn btn-primary">Submit</button>
91+
</EditForm>
92+
93+
@code {
94+
private SfUploader UploadObj;
95+
96+
public class Employee
97+
{
98+
[Required(ErrorMessage = "Please upload a file")]
99+
public List<UploaderUploadedFiles> files { get; set; }
100+
}
101+
102+
public Employee employee = new Employee();
103+
104+
public void OnSelect(SelectedEventArgs args)
105+
{
106+
this.employee.files = new List<UploaderUploadedFiles> { new UploaderUploadedFiles { Name = args.FilesData[0].Name, Type = args.FilesData[0].Type, Size = args.FilesData[0].Size } };
107+
}
108+
109+
private async Task OnChange(UploadChangeEventArgs args)
110+
{
111+
foreach (var file in args.Files)
112+
{
113+
if (file.FileInfo != null && file.File != null)
114+
{
115+
var path = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot", file.FileInfo.Name);
116+
using FileStream filestream = new FileStream(path, FileMode.Create, FileAccess.Write);
117+
await file.File.OpenReadStream(long.MaxValue).CopyToAsync(filestream);
118+
}
119+
}
120+
}
121+
122+
public void OnRemove()
123+
{
124+
this.employee.files = null;
125+
}
126+
127+
public async Task HandleValidSubmit()
128+
{
129+
await this.UploadObj.UploadAsync();
130+
}
131+
}
132+
```
133+
134+
{% previewsample "https://blazorplayground.syncfusion.com/embed/LNheNkBrgmbGBlgC?appbar=false&editor=false&result=true&errorlist=false&theme=bootstrap5" %}
135+
136+
![Blazor File Upload component within an EditForm, showing validation and submission.](./images/blazor-uploader-editform.gif)
137+
138+
## File Upload with DataForm Integration
139+
140+
The File Upload component can also be integrated into a Syncfusion `DataForm`, providing a streamlined way to create forms from a model. The example below shows how to save an uploaded file directly to the file system in a Blazor Server application when the form is submitted.
141+
142+
> This file-saving approach is only compatible with Blazor Server applications.
143+
144+
```cshtml
145+
@using Syncfusion.Blazor.DataForm
146+
@using System.ComponentModel.DataAnnotations
147+
@using Syncfusion.Blazor.Inputs
148+
@using System.IO
149+
150+
<SfDataForm ID="MyForm" Model="@UserModel" Width="50%" OnSubmit="Submit">
151+
<FormValidator>
152+
<DataAnnotationsValidator></DataAnnotationsValidator>
153+
</FormValidator>
154+
<FormItems>
155+
<FormItem Field="@nameof(UserModel.files)">
156+
<Template>
157+
<SfUploader @ref="UploadObj" AllowMultiple="false" AutoUpload="false" ID="UploadFiles">
158+
<UploaderEvents ValueChange="OnChange" OnRemove="OnRemove" FileSelected="OnSelect"></UploaderEvents>
159+
</SfUploader>
160+
</Template>
161+
</FormItem>
162+
</FormItems>
163+
</SfDataForm>
164+
165+
@code {
166+
private SfUploader UploadObj;
167+
168+
public class UserDataModel
169+
{
170+
[Required(ErrorMessage = "Please upload a file")]
171+
public List<UploaderUploadedFiles> files { get; set; }
172+
}
173+
174+
private UserDataModel UserModel = new UserDataModel();
175+
176+
private async Task OnChange(UploadChangeEventArgs args)
177+
{
178+
foreach (var file in args.Files)
179+
{
180+
if (file.FileInfo != null && file.File != null)
181+
{
182+
var path = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot", file.FileInfo.Name);
183+
using FileStream filestream = new FileStream(path, FileMode.Create, FileAccess.Write);
184+
await file.File.OpenReadStream(long.MaxValue).CopyToAsync(filestream);
185+
}
186+
}
187+
}
188+
189+
private void OnRemove()
190+
{
191+
this.UserModel.files = null;
192+
}
193+
194+
private void OnSelect(SelectedEventArgs args)
195+
{
196+
this.UserModel.files = new List<UploaderUploadedFiles> { new UploaderUploadedFiles { Name = args.FilesData[0].Name, Type = args.FilesData[0].Type, Size = args.FilesData[0].Size } };
197+
}
198+
199+
private async Task Submit(object args)
200+
{
201+
await this.UploadObj.UploadAsync();
202+
}
203+
}
204+
```
205+
206+
{% previewsample "https://blazorplayground.syncfusion.com/embed/BNBSDaBVKlbHqfgu?appbar=false&editor=false&result=true&errorlist=false&theme=bootstrap5" %}
207+
208+
![Blazor File Upload component within a Syncfusion DataForm.](./images/blazor-uploader-dataform.gif)
322 KB
Loading
339 KB
Loading

0 commit comments

Comments
 (0)