如果只有一个文件上传控件,我可以传递文件,但是当我使用多个文件上传控件时,我会得到null。
这是我的观点: -
<%@ Page Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage" %>
<asp:Content ID="indexTitle" ContentPlaceHolderID="TitleContent" runat="server">
Home Page - My ASP.NET MVC Application
</asp:Content>
<asp:Content ID="indexFeatured" ContentPlaceHolderID="FeaturedContent" runat="server">
</asp:Content>
<asp:Content ID="indexContent" ContentPlaceHolderID="MainContent" runat="server">
<% using (Html.BeginForm("Index", "Home", FormMethod.Post, new { enctype = "multipart/form-data" })) { %>
<input name="name" type="text" />
<input type="file" name="files1" value="" multiple="multiple"/>
<input type="file" name="files2" value="" multiple="multiple"/>
<input type="submit" value="Upload You Image" title="Uplad"/>
<% } %>
</asp:Content>
这是控制器动作: -
[HttpPost]
public JsonResult Index(HttpPostedFileBase[] files)
{
JsonResult result = new JsonResult();
foreach (HttpPostedFileBase file in files)
{
/*Geting the file name*/
string filename = System.IO.Path.GetFileName(file.FileName);
/*Saving the file in server folder*/
file.SaveAs(Server.MapPath("~/Images/" + filename));
string filepathtosave = "Images/" + filename;
/*HERE WILL BE YOUR CODE TO SAVE THE FILE DETAIL IN DATA BASE*/
}
return result;
}
答案 0 :(得分:1)
asp.net mvc modelbinding考虑了输入字段的名称。 action方法的参数与任何输入文件字段都不匹配。您需要修改它们,如
[HttpPost]
public JsonResult Index(HttpPostedFileBase[] files1, HttpPostedFileBase[] files2)
{
JsonResult result = new JsonResult();
foreach (HttpPostedFileBase file in files1)
{
/*Geting the file name*/
string filename = System.IO.Path.GetFileName(file.FileName);
/*Saving the file in server folder*/
file.SaveAs(Server.MapPath("~/Images/" + filename));
string filepathtosave = "Images/" + filename;
/*HERE WILL BE YOUR CODE TO SAVE THE FILE DETAIL IN DATA BASE*/
}
return result;
}
或者,如果您想要接收相同参数中的所有文件,您可以输入
<input type="file" name="files[0]" value="" multiple="multiple"/>
<input type="file" name="files[1]" value="" multiple="multiple"/>
这样,您就不需要更改操作方法的实现
答案 1 :(得分:1)
您可以做的最简单的事情是迭代Request.Files
:
[HttpPost]
public JsonResult Index()
{
JsonResult result = new JsonResult();
foreach (HttpPostedFileBase file in Request.Files)
{
...
}
return result;
}