public async Task <ActionResult> ChangeImage(Guid?id) { //CurrentAction.currentAction = "Post"; var post = await db.Posts.FindAsync(id); if (post == null) { return(HttpNotFound()); } var model = new ChangeImagePostViewModel { Id = post.Id, Image = post.Image }; return(View(model)); }
public async Task <ActionResult> ChangeImage(ChangeImagePostViewModel model) { //CurrentAction.currentAction = "Post"; if (ModelState.IsValid) { var post = await db.Posts.FindAsync(model.Id); if (post == null) { return(HttpNotFound()); } try { string image = ""; foreach (string item in Request.Files) { HttpPostedFileBase file = Request.Files[item]; if (file != null && file.ContentLength > 0) { //Định nghĩa đường dẫn lưu file trên server //ở đây mình lưu tại đường dẫn yourdomain/Uploads/ var originalDirectory = new DirectoryInfo(string.Format("{0}Uploads\\Posts\\", Server.MapPath(@"\"))); //Lưu trữ hình ảnh theo từng tháng trong năm var datePath = DateTime.Now.ToString("yyyy-MM"); string pathString = Path.Combine(originalDirectory.ToString(), datePath); bool isExists = Directory.Exists(pathString); if (!isExists) { Directory.CreateDirectory(pathString); } var path = string.Format("{0}\\{1}", pathString, file.FileName); string newFileName = file.FileName; //lấy đường dẫn lưu file sau khi kiểm tra tên file trên server có tồn tại hay không var newPath = ImageHelper.GetNewPathForDupes(path, ref newFileName); string serverPath = string.Format("/{0}/{1}/{2}", "Uploads", "Posts", datePath, newFileName); //Lưu hình ảnh Resize từ file sử dụng file.InputStream ImageHelper.SaveResizeImage(Image.FromStream(file.InputStream), 600, newPath); image = "/Uploads/Posts/" + datePath + "/" + newFileName; } } if (string.IsNullOrEmpty(image) == false) { // xóa image cũ nếu thay image mới string deletePath = Request.MapPath(post.Image); if (System.IO.File.Exists(deletePath) && post.Image != "/Uploads/Posts/def.jpg") { System.IO.File.Delete(deletePath); } post.Image = image; post.UpdatedDate = DateTime.Now; } await db.SaveChangesAsync(); return(RedirectToAction("Index", "Post", null)); } catch (Exception) { } } return(View(model)); }