使用Request.Files多文件上传["文件"] MVC
问题描述:
这是我的code。我想uplade 3档到我的数据库
This is my Code. I want to uplade 3 file into my database
先在查看我写这篇文章:
<%使用(Html.BeginForm(Actionname,控制器,FormMethod.Post,新{ENCTYPE =的multipart / form-data的})){%> .....
....
first in View I write this : <% using (Html.BeginForm(Actionname, Controller, FormMethod.Post, new {enctype="multipart/form-data"})){%> ..... ....
这是3档uplaoding:
and this is 3 file uplaoding:
<input type="file" name="files" id="FileUpload1" />
<input type="file" name="files" id="FileUpload2" />
<input type="file" name="files" id="FileUpload3" />
在控制器我用这个code:
In controller I use this code:
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:(
but the files always return NULL :(
请帮帮我,谢谢你。
答
试试这个:
<% 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");
}
}
这是一个有点清洁。
It's a bit cleaner.