这是我的代码。我想将3档文件升级到我的数据库
首先在View中我写这个: <%using(Html.BeginForm(Actionname,Controller,FormMethod.Post,new {enctype =“multipart / form-data”})){%> ..... ....
这是3个文件上传:
<input type="file" name="files" id="FileUpload1" />
<input type="file" name="files" id="FileUpload2" />
<input type="file" name="files" id="FileUpload3" />
在控制器中我使用此代码:
IEnumerable<HttpPostedFileBase> files = Request.Files["files"] as IEnumerable<HttpPostedFileBase>;
foreach (var file in files)
{
byte[] binaryData = null;
HttpPostedFileBase uploadedFile = file;
if (uploadedFile != null && uploadedFile.ContentLength > 0){
binaryData = new byte[uploadedFile.ContentLength];
uploadedFile.InputStream.Read(binaryData, 0,uploadedFile.ContentLength);
}
}
但文件总是返回NULL :(
请帮帮我,谢谢。
答案 0 :(得分:4)
请改为尝试:
<% using (Html.BeginForm("Index", "Home", FormMethod.Post, new { enctype = "multipart/form-data" })) {%>
<input type="file" name="files" id="FileUpload1" />
<input type="file" name="files" id="FileUpload2" />
<input type="file" name="files" id="FileUpload3" />
<input type="submit" value="Upload" />
<% } %>
和相应的控制器:
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
[HttpPost]
public ActionResult Index(IEnumerable<HttpPostedFileBase> files)
{
foreach (var file in files)
{
if (file.ContentLength > 0)
{
// TODO: do something with the uploaded file here
}
}
return RedirectToAction("Index");
}
}
它有点清洁。
答案 1 :(得分:1)
您应该使用:
IList<HttpPostedFileBase> files = Request.Files.GetMultiple("files")
代替。