Example #1
0
        public async Task <IActionResult> GetPhoto(int id)
        {
            Photo photo = await this.repository.GetPhotoAsync(id);

            if (photo == null)
            {
                return(NotFound());
            }

            ReturnPhotoViewModel photoViewModel = this.mapper.Map <ReturnPhotoViewModel>(photo);

            return(Ok(photo));
        }
Example #2
0
        public async Task <IActionResult> AddPhotoForUser(int userId, [FromForm] CreatePhotoViewModel photoViewModel)
        {
            if (userId != int.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value))
            {
                return(Unauthorized());
            }

            User user = await this.repository.GetUserAsync(userId);

            IFormFile file = photoViewModel.File;

            ImageUploadResult uploadResult = new ImageUploadResult();

            // TODO: Add validation to check if the file is actually a photo
            if (file.Length > 0)
            {
                using (Stream stream = file.OpenReadStream())
                {
                    ImageUploadParams uploadParams = new ImageUploadParams()
                    {
                        File           = new FileDescription(file.Name, stream),
                        Transformation = new Transformation().Width(500).Height(500).Crop("fill").Gravity("face")
                    };

                    uploadResult = this.cloudinary.Upload(uploadParams);
                }
            }

            photoViewModel.Url      = uploadResult.Url.AbsoluteUri;
            photoViewModel.PublicId = uploadResult.PublicId;

            Photo photo = this.mapper.Map <Photo>(photoViewModel);

            if (!user.Photos.Any())
            {
                photo.IsMain = true;
            }

            user.Photos.Add(photo);

            if (await this.repository.SaveAllAsync())
            {
                ReturnPhotoViewModel returnPhotoView = this.mapper.Map <ReturnPhotoViewModel>(photo);
                return(CreatedAtRoute("GetPhoto", new { userId = userId, id = photo.Id }, returnPhotoView));
            }

            return(BadRequest("Could not upload image"));
        }