C# 来自数据库的多个图像
我想上传多张图片并保存到数据库中。但在控制器操作中:上传更多照片。我在文件中看到我选择的文件,但如果通过以下行:file.SaveAspath;它只保存一个图像,然后转到ModelState.IsValid。因此,如何上传您选择的所有图像。多谢各位 我有这个: 控制器操作:C# 来自数据库的多个图像,c#,jquery-ui,asp.net-mvc-4,visual-studio-2012,entity-framework-4,C#,Jquery Ui,Asp.net Mvc 4,Visual Studio 2012,Entity Framework 4,我想上传多张图片并保存到数据库中。但在控制器操作中:上传更多照片。我在文件中看到我选择的文件,但如果通过以下行:file.SaveAspath;它只保存一个图像,然后转到ModelState.IsValid。因此,如何上传您选择的所有图像。多谢各位 我有这个: 控制器操作: [HttpPost] public ActionResult UploadMorePhotos(UserProfile userProfile, IEnumerable<HttpPoste
[HttpPost]
public ActionResult UploadMorePhotos(UserProfile userProfile, IEnumerable<HttpPostedFileBase>files)
{
foreach (var file in files)
{
if (file.ContentLength > 0)
{
var fileName = Path.GetFileName(file.FileName);
var path = Path.Combine(Server.MapPath("~/App_Data/uploads"), fileName);
file.SaveAs(path);
//ModelState.Clear();
}
if (ModelState.IsValid)
{
string username = User.Identity.Name;
// Get the userprofile
UserProfile user = db.userProfiles.FirstOrDefault(u => u.UserName.Equals(username));
// Update fields
user.Image = new byte[file.ContentLength];
file.InputStream.Read(user.Image, 0, file.ContentLength);
user.ImageMimeType = file.ContentType;
db.Entry(user).State = EntityState.Modified;
db.SaveChanges();
}
return Redirect(Url.Action("Edit", "Account") + "#tabs-3");
}
return View(userProfile);
}
public ActionResult GetImage(int id)
{
byte[] image = db.userProfiles.Where(p => p.Id == id).Select(img => img.Image).FirstOrDefault();
//var v = // FirstOrDefault(u => u.Id.Equals(itemId));
// image = v;
return File(image,"image/jpeg");
}
让我们把脂肪从你的循环中去掉:
foreach (var file in files)
{
if (file.ContentLength > 0)
{
file.SaveAs(path);
}
if (ModelState.IsValid)
{
db.SaveChanges();
}
return Redirect(Url.Action("Edit", "Account") + "#tabs-3");
}
您将在第一次迭代结束时从循环返回
如果你移除
return Redirect(Url.Action("Edit", "Account") + "#tabs-3");
你的循环应该完成了
更新
但是我想在上传完图片后继续关注第三页 然后替换
return View(userProfile);
与
确保在循环完成后返回。但我想在上传图像后保留在选项卡3上。然后,用它替换return ViewuserProfile,而不是删除它。一旦命中任何return语句,您的方法就会返回。但是最后一次返回是什么呢?return ViewuserProfile;}返回ViewuserProfile;}两次用户配置文件?
return View(userProfile);
}
foreach (var file in files)
{
if (file.ContentLength > 0)
{
file.SaveAs(path);
}
if (ModelState.IsValid)
{
db.SaveChanges();
}
return Redirect(Url.Action("Edit", "Account") + "#tabs-3");
}
return Redirect(Url.Action("Edit", "Account") + "#tabs-3");
return View(userProfile);
return Redirect(Url.Action("Edit", "Account") + "#tabs-3");