MVC4 图片上传
新增
new { enctype = "multipart/form-data" } 这个必须要有 @using (Html.BeginForm(Html.BeginForm("Create", "UserInfo", FormMethod.Post, new { enctype = "multipart/form-data" }))) { <div class="editor-label"> <span>图片</span> </div> <div class="editor-field"> <input type="file" name="filImgs"/> @* <input type="hidden" name="ImgUrl" value="@Model.img"/>*@ </div> <p> <input type="submit" value="上传" /> </p> }
[HttpPost] public ActionResult Create(UserInfo userinfo) { var file = Request.Files[0]; var img = //处理图片 userinfo.img = img; try { if (ModelState.IsValid) { db.userinfo.Add(userinfo); db.SaveChanges(); return RedirectToAction("Index"); } else { throw new Exception(); } } catch (Exception) { return View("Create"); } }
编辑
new { enctype = "multipart/form-data" } 这个必须要有 @using (Html.BeginForm(Html.BeginForm("edit", "UserInfo", FormMethod.Post, new { enctype = "multipart/form-data" }))) { <div class="editor-label"> <span>图片</span> </div> <div class="editor-field"> <input type="file" name="filImgs"/> @* <input type="hidden" name="ImgUrl" value="@Model.img"/>*@ </div> <p> <input type="submit" value="修改" /> </p> }
[HttpPost] public ActionResult Edit(int id,UserInfo user) { var userinfo = db.userinfo.Find(id); //ModelState.IsValid,此处相当于后台验证,防止前台验证因为各种情况被跳过或失效 try { bool updateRes = TryUpdateModel(userinfo);//如果字段符合则会赋值,否则保持原有 if (updateRes) { //图片 var file = Request.Files[0]; var img =// 图片处理 if (img.Length>0) { userinfo.img = img; } db.SaveChanges(); return RedirectToAction("Index"); } else { ModelState.AddModelError("", "更新失败!"); return View(userinfo); } } catch (Exception) { return View(userinfo); } }