我需要协助。我正在尝试使用<input type="file">
上传文件。这是我的观点:
@using (Html.BeginForm("BookAdd", "Admin", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<input type="file" name="files[0]" id="files[0]" />
<input type="file" name="files[1]" id="files[1]" />
<input type="submit" value="Upload Book" />
}
这是一个应处理上传文件的操作。
[HttpPost]
public ActionResult BookAdd(IEnumerable<HttpPostedFileBase> files)
{
// some actions
return View();
}
问题是"file"始终包含两个为空的元素。
该如何解决?
现在该是一些新闻了。看来我找到了问题,但我仍然不知道如何解决。看来,尽管事实是我在这里使用“multipart / form-data”:
@using (Html.BeginForm("BookAdd", "Admin", FormMethod.Post, new { enctype="multipart/form-data" }))
{
<input type="file" name="File" id="file1" />
<input type="file" name="File" id="file2" />
<input type="submit" value="Upload Book" />
}
Request.ContentType
在 Controller 中仍为“application / x-www-forum-urlencoded”。
最佳答案
只需删除输入字段名称中的方括号即可:
@using (Html.BeginForm("BookAdd", "Admin", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<input type="file" name="files" id="file1" />
<input type="file" name="files" id="file2" />
<input type="submit" value="Upload Book" />
}
更新:
在查看了示例项目后,您给我发送了问题,原因是您有2个嵌套表单。 HTML不允许这样做。在
_Layout.cshtml
中有一个表单,在BookAdd.cshtml
View 中有另一个表单。这就是为什么尽管您的内部表单具有enctype="multipart/form-data"
属性,但您得到了错误的Request.ContentType
的原因。因此,如果您希望这样做,则必须取消嵌套这些表格。同样在您发送给我的示例中,您的BookAdd
Controller 操作没有带文件列表的正确签名,但是我想这是由于您正在执行一些测试所致。
关于asp.net-mvc-3 - MVC。 HttpPostedFileBase始终为null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8159725/