C# 使用c上载多个文件时出现的问题#

C# 使用c上载多个文件时出现的问题#,c#,file,asp.net-mvc-4,C#,File,Asp.net Mvc 4,我正在尝试上载多个文件(在一次单击和上载中选择多个文件)。为此,我使用以下代码。我在MVC4中做这件事 @using (Html.BeginForm("Gallery", "Admin", FormMethod.Post, new {enctype="multipart/form-data", id = "GalleryForm" })) { @Html.ValidationSummary(); <div> Select the files to Upload&l

我正在尝试上载多个文件(在一次单击和上载中选择多个文件)。为此,我使用以下代码。我在MVC4中做这件事

@using (Html.BeginForm("Gallery", "Admin", FormMethod.Post, new  {enctype="multipart/form-data", id = "GalleryForm" }))
{
    @Html.ValidationSummary();

    <div> Select the files to Upload<br /> <input type="file" name="file" id="file" multiple="multiple" /><br /><br /></div>
    <div><input type="submit" name="submit" Value="Save"/></div>
}
@使用(Html.BeginForm(“Gallery”,“Admin”,FormMethod.Post,new{enctype=“multipart/formdata”,id=“GalleryForm”}))
{
@Html.ValidationSummary();
选择要上载的文件


}
控制器

[HttpPost]
public ActionResult Gallery(IEnumerable<HttpPostedFileBase> files)
{
    foreach (var file in files)
    {
        if (file.ContentLength > 0)
        {
            var fileName = Path.GetFileName(file.FileName);
            var path = Path.Combine(Server.MapPath("~/Images/Gallery/"), fileName);
            file.SaveAs(path);
         }
    }
    return RedirectToAction("Index");
}
[HttpPost]
公共操作结果库(IEnumerable文件)
{
foreach(文件中的var文件)
{
如果(file.ContentLength>0)
{
var fileName=Path.GetFileName(file.fileName);
var path=path.Combine(Server.MapPath(“~/Images/Gallery/”),文件名);
file.SaveAs(路径);
}
}
返回操作(“索引”);
}

如果我选择了多个文件,则会出现错误“超出最大请求长度”,当我选择单个文件并尝试上载时,会出现错误
“对象引用未设置为对象的实例”
。实际上,我想用这个表单上传单个和多个文件。这怎么可能呢。请帮帮我。提前感谢。

您的参数名称与表单输入元素名称不匹配,您应该在代码隐藏和html中使用“file”或“files”
name=“file”
应该是
name=“files”

重命名输入类型文件的
name
属性

<input type="file" name="files" id="file" multiple="multiple" />

对于第二个错误,即maximunn长度超过web配置中的更改

<configuration>
    <system.web>
        <httpRuntime maxRequestLength="1048576" />
    </system.web>
</configuration>

对于IIS7及以上版本,还需要添加以下行:

<system.webServer>
   <security>
      <requestFiltering>
         <requestLimits maxAllowedContentLength="1073741824" />
      </requestFiltering>
   </security>
 </system.webServer>


注意:maxAllowedContentLength以字节为单位测量,而maxRequestLength以千字节为单位测量,这就是此配置示例中的值不同的原因。(两者都相当于1 GB。)

需要更多信息:显示的哪一行代码给出了错误?可能是foreach。。由于参数名称不匹配而为null的文件。另请参见此问题:@DaviddCeFreitas:我想使用“单输入控件”上载多个文件有时我想使用此输入控件上载多个文件。但是这个代码只允许上传一个文件