在Razor Pages .NET 6中上传多个文件-提交空表单

7gyucuyw  于 2023-01-14  发布在  .NET
关注(0)|答案(1)|浏览(177)

我动态地构建我的表单,以允许根据分辨率要求上载多个图像。
RequiredDimensionsOptions集合有图像需求,例如1296 x450、916 x450等。我循环遍历这些图像,并为每个图像呈现一个File upload控件,因此(缩写)-每个图像都有一个唯一的ID:

<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 class="forceLeftMargin" 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>

然后,我可以使用一些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
        }

    }

问题是,当我尝试使用控件上传多个文件时,这些文件在Request.Form集合中不显示为文件,甚至不显示为提交的字段。

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

...解析为false。我有单个AntiForgeryRequestToken元素。当我上传单个文件时,它工作正常。
如何上传多个文件?
我很感激我可以使用多文件上传选项,但我想保持验证和用户体验的分辨率。

pgvzfuti

pgvzfuti1#

这可能有助于或给予更接近的解决方案:

在剃刀页.cshtml文件中。

@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" class="forceLeftMargin" 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>

.cs文件中

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

相关问题