【问题标题】:Not able to upload multiple files with IEnumerable<HttpPostedFileBase>无法使用 IEnumerable<HttpPostedFileBase> 上传多个文件
【发布时间】:2014-09-01 00:18:24
【问题描述】:

我有一个场景,用户选择 4 张图片上传,我需要将这四个文件绑定到我的模型并保存到文件夹中。但我面临的问题是我的模型在达到操作方法时将为空。

我的观点:

@using(@Html.BeginForm("fileUpload","Home",FormMethod.Post, new { enctype = "multipart/form-data"}))
{
<div>
    <h1>Auto Upload</h1>
</div>
<div>@Html.TextBoxFor(m => m.MyFile, new { id = "file1" , Type = "file" })</div>
<div>@Html.TextBoxFor(m => m.MyFile, new { id = "file2" , Type = "file" })</div>
<div>@Html.TextBoxFor(m => m.MyFile, new { id = "file3" , Type = "file" })</div>
<div>@Html.TextBoxFor(m => m.MyFile, new { id = "file4" , Type = "file" })</div>
<input type ="submit" name ="submit" />
}

我的模特:

public class MyModel
    {
        public IEnumerable<HttpPostedFileBase> MyFile { get; set; }
    }

控制器:当我在控制器的 fileUpload 方法中单击提交时,我得到 files = null。

        [HttpPost]
        public void fileUpload(IEnumerable<HttpPostedFileBase> files)
        {
            string s = "upload";
        }

与我平时的工作相比,我对文件上传的东西很陌生。

【问题讨论】:

    标签: c# asp.net asp.net-mvc asp.net-mvc-3 asp.net-mvc-4


    【解决方案1】:

    您使用相同的名称但不同的 id 显示相同的文本框四次,模型绑定器不知道您正在尝试发布一个名为 files 的集合。也不要在这里使用 TextBoxFor 帮助器,在这种情况下使用普通的旧 HTML 元素没有错。

    @using (@Html.BeginForm("fileUpload", "Home", FormMethod.Post, new { enctype = "multipart/form-data" }))
    {
        <label for="file1">File :</label>
        <input type="file" name="files" id="file1" />
    
        <label for="file2">File :</label>
        <input type="file" name="files" id="file2" />
    
        <label for="file3">File :</label>
        <input type="file" name="files" id="file3" />
    
        <label for="file4">File :</label>
        <input type="file" name="files" id="file4" />
    
        <input type="submit" value="Upload" />
    }
    

    然后您的控制器方法签名保持不变,但您会看到 files 集合已正确填充。

    [HttpPost]
    public void fileUpload(IEnumerable<HttpPostedFileBase> files)
    {
        foreach (var file in files)
        {
            // Validate size (in bytes), set your limit accordingly
            if (file.ContentLength > 0  && file.ContentLength <= 2097152)
            {
                // Do something with your files
            }
        }
    }
    

    要记住的重要一点是模型绑定基于表单元素的name 属性工作。按照你的方式,输入被渲染成&lt;input name="MyFile"&gt; 这样的东西,所以当发回服务器时,没有任何迹象表明它应该绑定到一个名为files 的集合。

    【讨论】:

    • 感谢 Dom,您的解决方案运行良好。但是我的模型还有一些我没有添加到模型中的属性,因为它不是必需的。即使我使用相同的代码也能正常工作
    • 是的,只需将您的控制器操作签名更新为 public void fileUpload(MyModel model, IEnumerable&lt;HttpPostedFileBase&gt; files) 并像往常一样处理您的模型。
    • 非常感谢 dom。您能告诉我如何在使用 JQuery 访问控制器操作方法之前将文件大小控制为最小和最大吗?
    • 我已经编辑了我的答案以展示如何在服务器端进行操作。但就如何使用 jQuery 而言,我无法帮助您,因为这不是我所熟悉的。通过快速搜索,我找到了this,这可能会为您指明正确的方向。
    猜你喜欢
    • 2018-12-06
    • 1970-01-01
    • 1970-01-01
    • 2013-07-10
    • 1970-01-01
    • 1970-01-01
    • 2021-08-23
    • 2013-03-02
    相关资源
    最近更新 更多