这是我的代码:
@using (Html.BeginForm("UploadImages", "Administration", new { _id = Model.Album.AlbumID, enctype = "multipart/form-data" }, FormMethod.Post))
{
<input type="file" name="fileUpload" id="file1" /><br />
<input type="file" name="fileUpload" id="file2" /><br />
<input type="file" name="fileUpload" id="file3" /><br />
<input name="addPhoto" type="submit" value="Добавить фото" />
}
[Authorize]
[HttpPost]
public ActionResult UploadImages(int _id, IEnumerable<HttpPostedFileBase> fileUpload)
{
gb_albumdbEntities1 entityes = new gb_albumdbEntities1();
foreach (var file in fileUpload)
{
if (file == null) continue; // **<---fileUpload items is always null!**
string path = AppDomain.CurrentDomain.BaseDirectory + "Photos/";
if (Path.GetFileName(file.FileName) != null)
{
string filename = file.GetHashCode().ToString();
string fullpath = Path.Combine(path, filename);
file.SaveAs(fullpath);
entityes.Photos.AddObject(new Photo() { AlbumID = _id, PhotoUrl = @"http://site.ru/Photos/" + filename });
}
}
entityes.SaveChanges();
return RedirectToAction("AlbumEdit", new { id = _id });
}
fileUpload项始终为null。问题出在哪里?Oo
UPD:网址后计算结果:
http://localhost:56193/Administration/UploadImages?_id=4&enctype=multipart%2Fform-data
答案 0 :(得分:2)
您的列表是否需要编号文件输入才能使模型绑定正常工作。在最简单的形式中,您的视图应如下所示:
<html>
<head>
<title>Index</title>
</head>
<body>
<div>
@using (Html.BeginForm("Index", "Upload", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
for (int i = 0; i < 3; i++)
{
@Html.TextBox(string.Format("fileUpload[{0}]", i), null, new { type="file" })<br />
}
<input name="submit" type="submit" value="Go" />
}
</div>
</body>
</html>
和您的控制人员:
public class UploadController : Controller
{
//
// GET: /Upload/
public ActionResult Index()
{
return View();
}
[HttpPost]
public ActionResult Index(IEnumerable<HttpPostedFileBase> fileUpload)
{
return View();
}
}
答案 1 :(得分:1)
尝试以下我自己用过的帖子。为我工作。
http://haacked.com/archive/2010/07/16/uploading-files-with-aspnetmvc.aspx