Example #1
0
        public async Task <IActionResult> Upload(int userId, PhotoForUpload photoForUpload)
        {
            if (userId != int.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value))
            {
                Unauthorized("Sorry, You are not Authorized");
            }

            var userFromRepo = await this.datingRepository.GetUser(userId);

            var file = photoForUpload.File;

            var uploadResult = new ImageUploadResult();

            if (file.Length > 0)
            {
                using (var stream = file.OpenReadStream())
                {
                    var parameters = new ImageUploadParams()
                    {
                        File = new FileDescription(file.Name, stream)
                    };
                    uploadResult = this._cloudinary.Upload(parameters);
                }
            }
            photoForUpload.Url      = uploadResult.Uri.ToString();
            photoForUpload.PublicId = uploadResult.PublicId;

            var photo = this._mapper.Map <Photo>(photoForUpload);

            if (!userFromRepo.Photos.Any(photo => photo.IsMain))
            {
                photo.IsMain = true;
            }
            userFromRepo.Photos.Add(photo);

            if (await datingRepository.SaveAll())
            {
                // return CreatedAtRoute()
                return(Ok());
            }
            else
            {
                return(BadRequest("Could not add the photo"));
            }
        }