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