public ActionResult Edit(BlogViewModel model) { HttpPostedFileBase upload = model.HeaderImageFile; Blog blog = Mapper.Map <Blog>(model); if (ModelState.IsValid) { if (upload != null && upload.ContentLength > 0) { string fileName = upload.FileName.Split('.')[0] + Guid.NewGuid() + "." + upload.FileName.Split('.')[1]; string serverPath = Server.MapPath("~/Images/" + fileName); string physicalPath = Path.Combine("Images/", fileName); CustomHttpPostedFile f = new CustomHttpPostedFile(upload.InputStream, "jpg", serverPath); f.SaveAs(serverPath); blog.ModifiedOn = DateTime.Now; Image image; if (blog.HeaderImage != null) { try { System.IO.File.Delete(blog.HeaderImage.ImageServerPath); } catch (IOException ex) { //TODO add logger } image = new Image() { Id = model.HeaderImage.Id, ImageName = upload.FileName, ImagePhysicalPath = physicalPath, ImageServerPath = serverPath, CreatedOn = DateTime.Now, Type = EImageType.HeaderImage }; _unitOfWork.Images.Update(image); blog.HeaderImage = image; } else { image = new Image() { ImageName = upload.FileName, ImagePhysicalPath = physicalPath, ImageServerPath = serverPath, CreatedOn = DateTime.Now, Type = EImageType.HeaderImage }; _unitOfWork.Images.Insert(image); blog.HeaderImage = image; } } _unitOfWork.Blogs.Update(blog); _unitOfWork.Save(); return(RedirectToAction("Index")); } return(View(blog)); }
public ActionResult Create(BlogViewModel model) { HttpPostedFileBase upload = model.HeaderImageFile; var user = _unitOfWork.User.GetById(User.Identity.GetUserId()); Blog blog = Mapper.Map <Blog>(model); if (ModelState.IsValid) { if (upload != null && upload.ContentLength > 0) { string fileName = upload.FileName.Split('.')[0] + Guid.NewGuid() + "." + upload.FileName.Split('.')[1]; string serverPath = Server.MapPath("~/Images/" + fileName); string physicalPath = Path.Combine("Images/", fileName); CustomHttpPostedFile f = new CustomHttpPostedFile(upload.InputStream, "jpg", serverPath); f.SaveAs(serverPath); Image image = new Image() { ImageName = upload.FileName, ImagePhysicalPath = physicalPath, ImageServerPath = serverPath, CreatedOn = DateTime.Now, Type = EImageType.HeaderImage }; blog.HeaderImage = image; } blog.CreatedOn = DateTime.Now; blog.ModifiedOn = DateTime.Now; blog.ApplicationUser = user; _unitOfWork.Blogs.Insert(blog); _unitOfWork.Save(); return(RedirectToAction("Index")); } return(View(blog)); }