Home > front end >  Uploading more than one file in Razor Pages .NET 6 - empty form submission
Uploading more than one file in Razor Pages .NET 6 - empty form submission

Time:01-12

I build my form dynamically to allow multiple images to be uploaded, as per resolution requirements.

The RequiredDimensionsOptions collection has image requirements, eg. 1296x450, 916x450, etc. I loop through these and render a File upload control for each, thusly (abbreviated) - with a unique ID for each:

<form enctype="multipart/form-data" method="post" id="uploadFiles">
@foreach (var requiredDimension in Model.RequiredDimensionsOptions)
{ // the ID will be something like "file-0000w0000h"
    <p>
        <label for="file-@(requiredDimension.Width)w@(requiredDimension.Height)h">@requiredDimension.Width x @requiredDimension.Height</label>
                        
        <input  id="file-@(requiredDimension.Width)w@(requiredDimension.Height)h" name="file-@(requiredDimension.Width)w@(requiredDimension.Height)h" type="file">                           
    </p>                    
}
<input type="submit" value="Upload files"/>
</form>

I can then get the files using some C#:

    public async Task<IActionResult> OnPostAsync()
    {
        foreach (IFormFile? file in Request.Form.Files) // Request.Form.Files is empty when I set more than 1 upload control with a file
        {
              // work with the uploaded files
        }

    }

The problem is that when I try to upload more than one file using the controls, the files do not appear in the Request.Form collection as files or even as submitted fields. So this:

Request.Form.Keys.Any(q=>q.StartsWith("file-"))

... resolves to false. I have the single AntiForgeryRequestToken element. When I upload a single file, it works fine.

How can I have multiple files uploaded?

I appreciate I could use a multiple-file upload option, but I want to maintain the resolutions for validation and user experience.

CodePudding user response:

This May help or give a closer solution:

in razor page .cshtml File.

@page
@model KafilWepAdmin.Pages.testingModel
@{
    var RequiredDimensionsOptions = new Dictionary<int, int>() { {1296, 450 }, { 916, 450 } };

}



<form method="post" enctype="multipart/form-data">

    @foreach (var requiredDimension in @RequiredDimensionsOptions)
    {
        <div>
            <label for=$"w{@requiredDimension.Key}h{@requiredDimension.Value}">@requiredDimension.Key x @requiredDimension.Value</label>

            <input type="file"  id=$"w{@requiredDimension.Key}h{@requiredDimension.Value}" name=$"w{@requiredDimension.Key}h{@requiredDimension.Value}">
        </div>
    }

    
    <button type="submit"  asp-page-handler="GetFiles">Upload Files</button>
</form>

in .cs File

public async Task<IActionResult> OnPostGetFilesAsync()
{
    var files = Request.Form.Files;
    foreach (var file in files)
    {
        // process the file
    }
    return Page();
}
  • Related