MVC图片上传

1 首先我们看一下如何上传

1.1 view

 

上传页面:

  1: @using (Html.BeginForm("Create", "Achievement", FormMethod.Post, new { enctype = "multipart/form-data" }))
  2: {
  3:      <div class="editor-label">
  4:             @Html.LabelFor(model => model.Pictures)
  5:         </div>
  6:         <div class="editor-field">
  7:             <div><input type="file" name="Image" /></div>
  8:         </div>
  9: }
这里需要注意的是BeginForm方法的参数
 

1.2 control

 
  1:  public ActionResult Create(Achivement achieve, HttpPostedFileBase image)
  2:         {
  3:             try
  4:             {
  5:                 
  6:                 if (image != null && image.ContentLength > 0)
  7:                 {
  8:                     string fileName = DateTime.Now.ToString("yyyyMMdd") + "-" + Path.GetFileName(image.FileName);
  9:                     string filePath = Path.Combine(Server.MapPath("~/Images"), fileName);
 10:                     image.SaveAs(filePath);
 11:                     achieve.Pictures = "~/Images/" + fileName ; 
 12:                 }
 13:                 m_achivementService.Create(achieve);
 14:                 return RedirectToAction("Index");
 15:             }
 16:             catch
 17:             {
 18:                 return View();
 19:             }
 20:         }
 
现在图片已上传到Images目录下,注意这里Pictures字段存的图片路径一定要带上“~”。
posted @ 2017-03-13 14:30  尘暮  阅读(273)  评论(0编辑  收藏  举报