【问题标题】:Issue in Uploading multiple files using c#使用 c# 上传多个文件的问题
【发布时间】:2014-01-03 10:06:14
【问题描述】:

我正在尝试上传多个文件,(单击选择多个文件并上传)。为此,我使用以下代码。我在 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>
}

控制器

[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");
}

如果我选择了多个文件,我收到错误“超出最大请求长度”,当我选择单个文件并尝试上传时,我收到错误"Object reference not set to an instance of an object"。实际上,我想使用相同的表单上传单个和多个文件。这怎么可能。请帮我。提前致谢。

【问题讨论】:

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


【解决方案1】:

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

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

对于第二个错误,即最大长度超过 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。)

【讨论】:

    【解决方案2】:

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

    【讨论】:

    • 有时我想使用此输入控件上传多个文件。但是这段代码只允许上传单个文件
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-31
    • 1970-01-01
    • 2013-07-10
    • 2012-08-30
    • 2012-05-13
    相关资源
    最近更新 更多