Hi @Kuler Master,
Inside the blazor app, you could also use the onclick inside a button to achieve the same thing, you could bind it with an upload method and show the file content after save completely.
More details, you could refer to below codes:
@page "/file-upload-1"
@using System
@using System.IO
@using Microsoft.AspNetCore.Hosting
@inject IWebHostEnvironment Environment
<PageTitle>File Upload 1</PageTitle>
<h1>File Upload Example 1</h1>
<p>
<label>
Max file size:
<input type="number" @bind="maxFileSize" />
</label>
</p>
<p>
<label>
Max allowed files:
<input type="number" @bind="maxAllowedFiles" />
</label>
</p>
<p>
<label>
Select files:
<InputFile OnChange="HandleFileSelected" multiple />
</label>
</p>
<button class="btn btn-primary" @onclick="UploadFiles" disabled="@(!filesSelected)">Upload</button>
@if (isLoading)
{
<p>Uploading...</p>
}
else
{
<ul>
@foreach (var file in loadedFiles)
{
<li>
<ul>
<li>Name: @file.Name</li>
<li>Last modified: @file.LastModified.ToString()</li>
<li>Size (bytes): @file.Size</li>
<li>Content type: @file.ContentType</li>
</ul>
</li>
}
</ul>
}
@code {
private List<IBrowserFile> loadedFiles = new();
private List<IBrowserFile> selectedFiles = new();
private long maxFileSize = 1024 * 15; // 15 KB
private int maxAllowedFiles = 3;
private bool isLoading;
private bool filesSelected = false;
private void HandleFileSelected(InputFileChangeEventArgs e)
{
// Save the selected files in memory for later upload
selectedFiles = e.GetMultipleFiles(maxAllowedFiles).ToList();
filesSelected = selectedFiles.Count > 0;
}
private async Task UploadFiles()
{
isLoading = true;
loadedFiles.Clear();
foreach (var file in selectedFiles)
{
try
{
// Generate a unique file name
var trustedFileName = Path.GetRandomFileName();
var path = Path.Combine(Environment.ContentRootPath,
Environment.EnvironmentName, "unsafe_uploads",
trustedFileName);
// Save the file to the server
await using FileStream fs = new(path, FileMode.Create);
await file.OpenReadStream(maxFileSize).CopyToAsync(fs);
loadedFiles.Add(file); // Add to the list of uploaded files
}
catch (Exception ex)
{
// Handle the exception (e.g., log it)
}
}
isLoading = false;
filesSelected = false;
}
}
Result:
If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.
Best Regards,
Brando