public async Task <IActionResult> AddPhotoForUser(int userId, PhotoForCreatingDTO photoDTO) { var user = await this.datingRepository.GetUser(userId); if (user == null) { return(BadRequest("Could not find user")); } var currentUserId = int.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value); if (user.Id != currentUserId) { return(Unauthorized()); } var file = photoDTO.File; var uploadResult = new ImageUploadResult(); if (file.Length > 0) { using (var stream = file.OpenReadStream()) { var uploadParams = new ImageUploadParams() { File = new FileDescription(file.Name, stream), Transformation = new Transformation().Width(1000).Height(1000).Crop("fill").Gravity("face") }; uploadResult = this.cloudinary.Upload(uploadParams); } } photoDTO.Url = uploadResult.Uri.ToString(); photoDTO.PublicId = uploadResult.PublicId; var photo = this.mapper.Map <Photo>(photoDTO); photo.User = user; if (!user.Photos.Any(m => m.IsMain)) { photo.IsMain = true; } user.Photos.Add(photo); if (await this.datingRepository.SaveAll()) { var photoForReturn = this.mapper.Map <PhotoForReturnDTO>(photo); return(CreatedAtRoute("GetPhoto", new { id = photo.Id }, photoForReturn)); } return(BadRequest("Could not add the photo")); }
public async Task <IActionResult> AddPhoto(int userId, [FromForm] PhotoForCreatingDTO photoForCreating) { if (userId != int.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value)) { return(StatusCode(401, "Unauthorize")); } var userFromRepo = await _repo.GetUser(userId); var file = photoForCreating.File; var uploadResult = new ImageUploadResult(); if (file == null) { return(BadRequest()); } if (file.Length > 0) { using (var stream = file.OpenReadStream()) { var uploadParam = new ImageUploadParams() { File = new FileDescription(file.Name, stream), Transformation = new Transformation().Width(450).Height(450).Crop("fill").Gravity("face") }; uploadResult = _cloudinary.Upload(uploadParam); } } else if (file == null) { return(BadRequest()); } photoForCreating.Url = uploadResult.Uri.ToString(); photoForCreating.PublicId = uploadResult.PublicId; var photo = _mapper.Map <Photo>(photoForCreating); if (!userFromRepo.Photos.Any()) { photo.IsMain = true; } userFromRepo.Photos.Add(photo); if (await _repo.SaveAll()) { var photoForReturn = _mapper.Map <PhotoForReturnDTO>(photo); return(CreatedAtRoute("GetPhoto", new { id = photo.Id }, photoForReturn)); } return(BadRequest("Could not add photo")); }