public async Task <IActionResult> Create([Bind("Id,Upload,Photo,ProductId")] SmallSizePhoto smallsizePhoto) { if (smallsizePhoto.Upload == null) { ModelState.AddModelError("Upload", "The Photo field is required."); } else { if (smallsizePhoto.Upload.ContentType != "image/jpeg" && smallsizePhoto.Upload.ContentType != "image/png" && smallsizePhoto.Upload.ContentType != "image/gif") { ModelState.AddModelError("Upload", "You can only download png, jpg or gif file"); } if (smallsizePhoto.Upload.Length > 1048576) { ModelState.AddModelError("Upload", "The file size can be a maximum of 1 MB"); } } if (ModelState.IsValid) { var fileName = _fileManager.Upload(smallsizePhoto.Upload); smallsizePhoto.Photo = fileName; _context.Add(smallsizePhoto); await _context.SaveChangesAsync(); return(RedirectToAction(nameof(Index))); } ViewData["ProductId"] = new SelectList(_context.Products, "Id", "Name", smallsizePhoto.ProductId); return(View(smallsizePhoto)); }
public async Task <IActionResult> Edit(int id, [Bind("Id,Upload,Photo,ProductId")] SmallSizePhoto smallsizePhoto) { if (id != smallsizePhoto.Id) { return(NotFound()); } if (smallsizePhoto.Upload == null) { ModelState.AddModelError("Upload", "The Photo field is required."); } if (ModelState.IsValid) { try { if (smallsizePhoto.Upload != null) { if (smallsizePhoto.Upload.ContentType != "image/jpeg" && smallsizePhoto.Upload.ContentType != "image/png" && smallsizePhoto.Upload.ContentType != "image/gif") { ModelState.AddModelError("Upload", "You can only download png, jpg or gif file"); return(View(smallsizePhoto)); } if (smallsizePhoto.Upload.Length > 1048576) { ModelState.AddModelError("Upload", "The file size can be a maximum of 1 MB"); return(View(smallsizePhoto)); } var oldFile = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot", "uploads", smallsizePhoto.Photo); _fileManager.Delete(oldFile); var fileName = _fileManager.Upload(smallsizePhoto.Upload, "wwwroot/uploads"); smallsizePhoto.Photo = fileName; } _context.Update(smallsizePhoto); await _context.SaveChangesAsync(); } catch (DbUpdateConcurrencyException) { if (!SmallsizePhotoExsist(smallsizePhoto.Id)) { return(NotFound()); } else { throw; } } return(RedirectToAction(nameof(Index))); } ViewData["ProductId"] = new SelectList(_context.Products, "Id", "Name", smallsizePhoto.ProductId); return(View(smallsizePhoto)); }