[英]Issue in Uploading multiple files using c#
我正在尝试上传多个文件(一次单击即可选择多个文件并上传)。 为此,我正在使用以下代码。 我在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"
。 实际上,我想使用这种相同的形式上传单个和多个文件。 这怎么可能。 请帮我。 提前致谢。
重命名输入类型文件的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。)
您的参数名称与表单输入元素名称不匹配,您应该在后面的代码和html中使用“ file”或“ files”。 name="file"
应该是name="files"
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.