How do I upload files in Blazor?
This code will help you to understand how to upload files in Blazor.
To upload files in Blazor applications, install the NuGet package, BlazorInputFile. This package has the component, InputFile that is used to upload files.
You also need to include the input file scripts in HTML and add BlazorInputs to the _Imports.razor file.
[_Host.cshtml]
<script src="_content/BlazorInputFile/inputfile.js"></script>
[index.razor]
@page "/upload"
<h3>Upload</h3>
<InputFile OnChange="HandleFileSelected" class="btn-primary"/>
@if (file != null)
{
<p>Name: @file.Name</p>
<p>Size in bytes: @file.Size</p>
<p>Last modified date: @file.LastModified.ToShortDateString()</p>
<p>Content type (not always supplied by the browser): @file.Type</p>
}
@code {
IFileListEntry file;
void HandleFileSelected(IFileListEntry[] files)
{
file = files.FirstOrDefault();
}
}
You can handle multiple file uploads by adding multiple attribute to the InputFile component.
@page "/multiupload"
<h3>Multiple File Upload</h3>
<InputFile multiple OnChange="HandleFileSelected" class="btn-primary"/>
@if (file != null)
{
<p>Name: @file.Name</p>
<p>Size in bytes: @file.Size</p>
<p>Last modified date: @file.LastModified.ToShortDateString()</p>
<p>Content type (not always supplied by the browser): @file.Type</p>
}
@code {
IFileListEntry file;
void HandleFileSelected(IFileListEntry[] files)
{
file = files.FirstOrDefault();
}
}
I would suggest you check the below link for better understanding:
https://blog.stevensanderson.com/2019/09/13/blazor-inputfile/