Skip to content

Commit d4522ba

Browse files
Merge pull request #6625 from syncfusion-content/983306-dev-file-up-tem
983306: Re-structing the template section of File uploader.
2 parents 286e521 + 4df0cb9 commit d4522ba

File tree

1 file changed

+50
-54
lines changed

1 file changed

+50
-54
lines changed

blazor/file-upload/template.md

Lines changed: 50 additions & 54 deletions
Original file line numberDiff line numberDiff line change
@@ -1,66 +1,69 @@
11
---
22
layout: post
33
title: Template in Blazor File Upload Component | Syncfusion
4-
description: Checkout and learn here about Template in Syncfusion Blazor File Upload component and much more details.
4+
description: Learn how to customize the Syncfusion Blazor File Upload component's appearance using templates, including how to add a progress bar.
55
platform: Blazor
66
control: File Upload
77
documentation: ug
88
---
99

1010
# Template in Blazor File Upload Component
1111

12-
The template feature customizes how each file item is rendered in the uploader UI. It enables full control over layout and styling for file details such as name, size, and status, so the interface can match application design requirements and provide a tailored user experience.
12+
The Blazor File Upload component allows for the customization of the file list items by using a template. This provides the flexibility to define the structure and styling of individual file elements, such as the file name, size, and status. A custom template can create a tailored and visually appealing file upload interface that aligns with an application's design and user experience requirements.
1313

1414
### With server-side API endpoint
1515

16-
Use a template with server endpoints when uploads are processed by a backend. The template controls only the display of file items; the upload flow still uses SaveUrl and RemoveUrl.
17-
1816
```cshtml
1917
@using Syncfusion.Blazor.Inputs
2018
2119
<SfUploader ID="Files" AutoUpload="false">
2220
<UploaderAsyncSettings SaveUrl="https://blazor.syncfusion.com/services/production/api/FileUploader/Save"
2321
RemoveUrl="https://blazor.syncfusion.com/services/production/api/FileUploader/Remove"></UploaderAsyncSettings>
2422
<UploaderTemplates>
25-
<Template>
26-
<div class="name file-name" title="@(context.Name)">File Name : @(context.Name)</div>
27-
<div class="file-size">File Size : @(context.Size)</div>
28-
<div class="e-file-status">File Status : @(context.Status)</div>
23+
<Template Context="context">
24+
<div style="padding: 10px;">
25+
<div class="name file-name" title="@context.Name">File Name : @context.Name</div>
26+
<div class="file-size">File Size : @context.Size</div>
27+
<div class="e-file-status">File Status : @context.Status</div>
28+
</div>
2929
</Template>
3030
</UploaderTemplates>
3131
</SfUploader>
3232
```
3333
### Without server-side API endpoint
3434

35-
Use a template without server endpoints when handling files locally (for example, demos or trusted environments). The template syntax and available context properties are the same as the server-backed example.
36-
3735
```cshtml
3836
@using Syncfusion.Blazor.Inputs
3937
4038
<SfUploader ID="Files" AutoUpload="false">
4139
<UploaderTemplates>
42-
<Template>
43-
<div class="name file-name" title="@(context.Name)">File Name : @(context.Name)</div>
44-
<div class="file-size">File Size : @(context.Size)</div>
45-
<div class="e-file-status">File Status : @(context.Status)</div>
40+
<Template Context="context">
41+
<div style="padding: 10px;">
42+
<div class="name file-name" title="@context.Name">File Name : @context.Name</div>
43+
<div class="file-size">File Size : @context.Size</div>
44+
<div class="e-file-status">File Status : @context.Status</div>
45+
</div>
4646
</Template>
4747
</UploaderTemplates>
4848
</SfUploader>
4949
```
5050

51-
### Adding progressbar using template
51+
{% previewsample "https://blazorplayground.syncfusion.com/embed/rZrSZOLhhmAhbeZR?appbar=false&editor=false&result=true&errorlist=false&theme=bootstrap5" %}
52+
53+
## Adding a progress bar using a template
5254

53-
When using a custom file template, the built-in progress bar is not shown. The following example disables the default progress indicator (ShowProgressBar=false), renders a custom progress element in the template, and updates it during stream read/write in the ValueChange event. The template displays file name, size, progress, and status, and toggles remove/delete icons based on item state. In browser-only environments (such as WebAssembly), write streams to appropriate storage or a server API; writing directly to the local file system is supported in server/desktop contexts.
55+
When using a file upload template, the default progress bar is not displayed in the UI. A progress bar can be added within the template, and its progress can be updated by reading and writing to the stream in the `ValueChange` event. The following code snippet demonstrates how to add a progress bar to a Blazor File Upload component using a custom template. The custom template includes elements to display the file name, size, progress bar, and file status.
5456

5557
```cshtml
5658
@using Syncfusion.Blazor.Inputs
5759
@using Syncfusion.Blazor.ProgressBar
58-
<SfUploader @ref="@uploderObj" ID="UploadFiles" MaxFileSize="100000000000" ShowProgressBar = "false">
59-
<UploaderEvents BeforeUpload="onBeforeUpload" Success="onSuccess" ValueChange="onChange"></UploaderEvents>
60+
61+
<SfUploader @ref="@uploaderObj" ID="UploadFiles" MaxFileSize="100000000000" ShowProgressBar="false">
62+
<UploaderEvents BeforeUpload="OnBeforeUpload" Success="OnSuccess" ValueChange="OnChange"></UploaderEvents>
6063
<UploaderTemplates>
61-
<Template>
64+
<Template Context="context">
6265
<span class="e-file-container">
63-
<span class="e-file-name" title="@(context.Name)">@this.GetFileName(context.Name)</span>
66+
<span class="e-file-name" title="@context.Name">@GetFileName(context.Name)</span>
6467
<span class="e-file-type">@("." + context.Type)</span>
6568
@if (context.Size > 0)
6669
{
@@ -71,9 +74,9 @@ When using a custom file template, the built-in progress bar is not shown. The f
7174
{
7275
<span class="e-upload-progress-wrap">
7376
<span class="e-progress-inner-wrap">
74-
<progressbar class="@("e-upload-progress-bar" + " " + "e-upload-progress")" value="0" max="100" style="width: @(ProgressValue.ToString() + "%")"></progressbar>
77+
<progress class="@("e-upload-progress-bar" + " " + "e-upload-progress")" value="0" max="100" style="width: @(ProgressValue + "%")"></progress>
7578
</span>
76-
<span class="e-progress-bar-text">@(ProgressValue.ToString() + "%")</span>
79+
<span class="e-progress-bar-text">@(ProgressValue + "%")</span>
7780
</span>
7881
}
7982
@if (fileStates.ContainsKey(context.Name) && fileStates[context.Name] && context.Status == "File uploaded successfully")
@@ -90,112 +93,103 @@ When using a custom file template, the built-in progress bar is not shown. The f
9093
}
9194
@if (fileStates.ContainsKey(context.Name) && fileStates[context.Name] && context.Status == "File uploaded successfully")
9295
{
93-
<span class="e-icons e-file-delete-btn @this.RemoveIconDisable" id="deleteIcon" title="Delete" @onclick="(args) => ClickHandler(context)"></span>
96+
<span class="e-icons e-file-delete-btn @RemoveIconDisable" id="deleteIcon" title="Delete" @onclick="(args) => ClickHandler(context)"></span>
9497
}
9598
else
9699
{
97-
<span class="e-icons e-file-remove-btn @this.RemoveIconDisable" id="removeIcon" title="Remove" @onclick="(args) => ClickHandler(context)"></span>
100+
<span class="e-icons e-file-remove-btn @RemoveIconDisable" id="removeIcon" title="Remove" @onclick="(args) => ClickHandler(context)"></span>
98101
}
99102
</span>
100-
101103
</Template>
102104
</UploaderTemplates>
103105
</SfUploader>
106+
104107
@code {
105-
private SfUploader uploderObj;
106-
public bool isVisible { get; set; } = false;
107-
private FileInfo CurrentFile {get; set;}
108+
private SfUploader uploaderObj;
109+
private FileInfo CurrentFile { get; set; }
108110
public string fileSize { get; set; } = "0";
109111
public string RemoveIconDisable = string.Empty;
110-
#pragma warning disable CA2213 // Disposable fields should be disposed
111112
private readonly SemaphoreSlim FileSemaphore = new SemaphoreSlim(1);
112-
#pragma warning restore CA2213 // Disposable fields should be disposed
113113
private decimal ProgressValue { get; set; } = 0;
114114
private Dictionary<string, bool> fileStates = new Dictionary<string, bool>();
115+
115116
public string CalculateFileSize(double size)
116117
{
117-
string fileSizeStr = "";
118118
if (size >= 1024 * 1024)
119119
{
120-
return fileSizeStr = $"{size / (1024f * 1024f):0.00} MB";
120+
return $"{size / (1024f * 1024f):0.00} MB";
121121
}
122122
else if (size >= 1024)
123123
{
124-
return fileSizeStr = $"{size / 1024f:0.00} KB";
124+
return $"{size / 1024f:0.00} KB";
125125
}
126126
else
127127
{
128-
return fileSizeStr = $"{size} bytes";
128+
return $"{size} bytes";
129129
}
130130
}
131+
131132
private string GetFileName(string fileName)
132133
{
133134
string type = GetFileType(fileName);
134135
string[] names = fileName.Split(new string[] { "." + type }, StringSplitOptions.None);
135136
return names[0];
136137
}
138+
137139
private string GetFileType(string name)
138-
#pragma warning restore CA1822 // Mark members as static
139140
{
140141
string extension = string.Empty;
141142
int index = name.LastIndexOf('.');
142143
if (index > 0)
143144
{
144145
extension = name.Substring(index + 1);
145146
}
146-
147-
return (!string.IsNullOrEmpty(extension)) ? extension : string.Empty;
148-
}
149-
private async Task onFileRemove()
150-
{
151-
await uploderObj.RemoveAsync();
147+
return !string.IsNullOrEmpty(extension) ? extension : string.Empty;
152148
}
149+
153150
public async Task ClickHandler(FileInfo context)
154151
{
155-
await uploderObj.RemoveAsync(new FileInfo[] { context });
152+
await uploaderObj.RemoveAsync(new FileInfo[] { context });
156153
}
157-
public void onBeforeUpload(BeforeUploadEventArgs args)
154+
155+
public void OnBeforeUpload(BeforeUploadEventArgs args)
158156
{
159157
foreach (var file in args.FilesData)
160158
{
161159
fileStates[file.Name] = false;
162160
}
163161
}
164-
public void onSuccess(SuccessEventArgs args)
162+
163+
public void OnSuccess(SuccessEventArgs args)
165164
{
166-
//fileStates[args.File.Name] = false;
167-
isVisible = false;
168-
this.ProgressValue = 0;
165+
ProgressValue = 0;
169166
}
170-
171-
public async Task onChange(UploadChangeEventArgs args)
167+
168+
public async Task OnChange(UploadChangeEventArgs args)
172169
{
173170
await FileSemaphore.WaitAsync();
174171
try
175172
{
176173
foreach (var file in args.Files)
177174
{
178-
var path = @"" + file.FileInfo.Name;
175+
var path = Path.Combine(Path.GetTempPath(), file.FileInfo.Name);
179176
CurrentFile = file.FileInfo;
180177
CurrentFile.Status = "Uploading";
181178
await using FileStream writeStream = new(path, FileMode.Create);
182179
using var readStream = file.File.OpenReadStream(file.File.Size);
183180
var bytesRead = 0;
184-
var totalRead = 0;
185181
var buffer = new byte[1024 * 10];
186182
187183
while ((bytesRead = await readStream.ReadAsync(buffer)) != 0)
188184
{
189185
RemoveIconDisable = "e-disabled";
190-
totalRead += bytesRead;
191186
await writeStream.WriteAsync(buffer, 0, bytesRead);
192187
ProgressValue = (long)((decimal)readStream.Position * 100) / readStream.Length;
193188
StateHasChanged();
194189
}
195190
CurrentFile.Status = "File uploaded successfully";
196191
RemoveIconDisable = string.Empty;
197192
fileStates[file.FileInfo.Name] = true;
198-
199193
}
200194
}
201195
catch (Exception ex)
@@ -211,4 +205,6 @@ When using a custom file template, the built-in progress bar is not shown. The f
211205
}
212206
```
213207

214-
![Blazor FileUpload with Chunk Upload](./images/blazor-template-progressbar.gif)
208+
{% previewsample "https://blazorplayground.syncfusion.com/embed/LNLytYhhLmmEGpkj?appbar=false&editor=false&result=true&errorlist=false&theme=bootstrap5" %}
209+
210+
![Blazor File Upload with a custom template and progress bar](./images/blazor-template-progressbar.gif)

0 commit comments

Comments
 (0)