// GET: Admin/Pictures/Edit/5 public async Task <IActionResult> Edit(int?id) { if (id == null) { return(NotFound()); } var picture = await _bll.Pictures.FindAsync(id); if (picture == null) { return(NotFound()); } var vm = new PictureEditViewModel { Picture = picture, OldFileName = Path.GetFileName(picture.Path), OldPicturePath = Path.Combine(_appEnvironment.ContentRootPath, "wwwroot", Path.Combine(picture.Path.Split("/"))) }; return(View(vm)); }
public async Task <IActionResult> Edit(int id, PictureEditViewModel vm, IFormFile file) { if (id != vm.Picture.Id) { return(NotFound()); } if (!vm.PictureFromUrl && file != null && file.Length > 0) { if (file.Length > 4194304) { ModelState.AddModelError(string.Empty, Resources.Domain.PictureView.Picture.FileTooBigError); } var fileExtension = Path.GetExtension(file.FileName); if (!_imageExtensions.Contains(fileExtension.ToUpper())) { ModelState.AddModelError(string.Empty, Resources.Domain.PictureView.Picture.FileFormatError + string.Join(',', _imageExtensions) + "."); } if (ModelState.ErrorCount > 0) { return(View(vm)); } if (vm.OldFileName != file.FileName) { // Delete old image if (System.IO.File.Exists(vm.OldPicturePath)) { System.IO.File.Delete(vm.OldPicturePath); } } // Create new picture path var newImagePath = Path.Combine(_appEnvironment.ContentRootPath, "wwwroot", "Images", BackgroundDirectory, file.FileName); vm.Picture.Path = newImagePath.Substring(newImagePath.IndexOf("Images", StringComparison.Ordinal) - 1).Replace("\\", "/"); try { // Copy picture to path await using var fileStream = new FileStream(newImagePath, FileMode.Create); await file.CopyToAsync(fileStream); } catch (Exception e) { throw new Exception(e.Message); } } vm.Picture.ChangedAt = DateTime.Now; vm.Picture.ChangedBy = _userManager.GetUserId(User); ModelState.Clear(); TryValidateModel(vm.Picture); if (ModelState.IsValid) { try { _bll.Pictures.Update(vm.Picture); await _bll.SaveChangesAsync(); } catch (DbUpdateConcurrencyException) { if (!PictureExists(vm.Picture.Id)) { return(NotFound()); } else { throw; } } return(RedirectToAction("Index", "ScreenSettings")); } return(View(vm)); }