How do I save file on form submit

Kuler Master 386 Reputation points
2024-12-27T16:34:04.0766667+00:00

Hello,

As mentioned in the title, I want to save the file to the server. In the past, we were using SaveAs but in Blazor I can't get a reference of PostedFile directly.

 <div class="row pb-3">
     <div class="col">
         <label class="form-label mb-0">@_localizer["Label_Id"]</label>
         <InputFile class="form-control" id="Id" @bind-Value="@application.FileId" />         
        <ValidationMessage For="@(() => application.FileId)" />      
    </div>
</div>

Thanks in advance

ASP.NET Core
ASP.NET Core
A set of technologies in the .NET Framework for building web applications and XML web services.
4,719 questions
Blazor
Blazor
A free and open-source web framework that enables developers to create web apps using C# and HTML being developed by Microsoft.
1,640 questions
ASP.NET
ASP.NET
A set of technologies in the .NET Framework for building web applications and XML web services.
3,553 questions
{count} votes

Accepted answer
  1. Brando Zhang-MSFT 3,876 Reputation points Microsoft Vendor
    2025-01-02T06:17:33.94+00:00

    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:

    User's image


    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

    1 person found this answer helpful.
    0 comments No comments

1 additional answer

Sort by: Most helpful
  1. Bruce (SqlWork.com) 68,876 Reputation points
    2024-12-27T17:04:25.5666667+00:00

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.