public async Task <IActionResult> UploadProfilePicture([FromForm] ProfilePictureRequest request) { var image = request.Image; List <string> AcceptableImageExtentions = new List <string> { ".jpg", ".jpeg", ".png" }; string fileExtention = System.IO.Path.GetExtension(image.FileName); if (!AcceptableImageExtentions.Contains(fileExtention)) { return(new BadRequestObjectResult("Image must be png, jpg or jpeg")); } if (image.Length > 10485760) { return(new BadRequestObjectResult("Max 10 MB")); } var user = await userRepository.Get(DefaultUserId); if (user.ProfilePicture != null) { System.IO.File.Delete(Path.Combine(Path.Combine(Directory.GetCurrentDirectory(), "Images"), Path.GetFileName(user.ProfilePicture))); } var fileName = Guid.NewGuid().ToString() + fileExtention; if (image.Length > 0) { using (var fileStream = new FileStream(Path.Combine(Path.Combine(Directory.GetCurrentDirectory(), "Images"), fileName), FileMode.Create)) { image.CopyTo(fileStream); } } user.ProfilePicture = "/images/" + fileName; await userRepository.Update(user); await userRepository.SaveChanges(); return(new OkResult()); }
public ActionResult <User> UploadPicture([FromBody] ProfilePictureRequest request) { try { byte[] binaryContent = System.IO.File.ReadAllBytes(request.Filename); if (binaryContent == null) { return(BadRequest("Error with file!")); } var user = _userService.Get(request.UserId); if (user == null) { return(NotFound()); } user.ProfilePicture = binaryContent; _userService.Update(request.UserId, user); return(user); } catch (System.IO.FileNotFoundException e) { return(BadRequest(e)); } }