Exemplo n.º 1
0
        public IActionResult CreateImage([FromBody] ImageForCreationDto imageForCreation)
        {
            if (imageForCreation == null)
            {
                return(BadRequest());
            }

            if (!ModelState.IsValid)
            {
                // return 422 - Unprocessable Entity when validation fails
                return(new Helpers.UnprocessableEntityObjectResult(ModelState));
            }

            // Automapper maps only the Title in our configuration
            var imageEntity = Mapper.Map <Entities.Image>(imageForCreation);

            // Create an image from the passed-in bytes (Base64), and
            // set the filename on the image

            // get this environment's web root path (the path
            // from which static content, like an image, is served)
            var webRootPath = _hostingEnvironment.WebRootPath;

            // create the filename
            string fileName = Guid.NewGuid().ToString() + ".jpg";

            // the full file path
            var filePath = Path.Combine($"{webRootPath}/images/{fileName}");

            // write bytes and auto-close stream
            System.IO.File.WriteAllBytes(filePath, imageForCreation.Bytes);

            // fill out the filename
            imageEntity.FileName = fileName;

            // fill in OwnerId
            var ownerId = User.Claims.FirstOrDefault(o => o.Type == "sub").Value;

            imageEntity.OwnerId = ownerId;

            // add and save.
            _galleryRepository.AddImage(imageEntity);

            if (!_galleryRepository.Save())
            {
                throw new Exception($"Adding an image failed on save.");
            }

            var imageToReturn = Mapper.Map <ImageDto>(imageEntity);

            return(CreatedAtRoute("GetImage",
                                  new { id = imageToReturn.Id },
                                  imageToReturn));
        }
        public async Task <IActionResult> AddImageForUser(int userId, [FromForm] ImageForCreationDto imageForCreationDto)
        {
            if (userId != int.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value))
            {
                return(Unauthorized());
            }

            var userFromRepo = await _repo.GetUser(userId);

            var file = imageForCreationDto.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(500).Height(500).Crop("limit")
                    };

                    uploadResult = _cloudinary.Upload(uploadParams);
                }
            }

            imageForCreationDto.Url      = uploadResult.Uri.ToString();
            imageForCreationDto.PublicId = uploadResult.PublicId;

            var image = _mapper.Map <Image>(imageForCreationDto);

            if (!userFromRepo.Images.Any(i => i.IsMain))
            {
                image.IsMain = true;
            }

            userFromRepo.Images.Add(image);

            if (await _repo.SaveAll())
            {
                var imageToReturn = _mapper.Map <ImageForReturnDto>(image);
                return(CreatedAtRoute("GetImage", new { id = image.Id }, imageToReturn));
            }

            return(BadRequest("Could not add the photo"));
        }
Exemplo n.º 3
0
        public async Task <IActionResult> CreateImage([FromBody] ImageForCreationDto image)
        {
            if (image == null)
            {
                return(BadRequest("ImageDto object is null."));
            }
            else
            {
                var imageEntity = _mapper.Map <Image>(image);
                _repository.Image.CreateImage(imageEntity);
                await _repository.SaveAsync();

                var imageToReturn = _mapper.Map <ImageDto>(imageEntity);
                return(CreatedAtRoute("GetImage", new { id = imageToReturn.Id }, imageToReturn));
            }
        }
Exemplo n.º 4
0
        public async Task <IActionResult> AddPhotoForToDo(int todoId,
                                                          [FromForm] ImageForCreationDto photoForCreationDto)
        {
            int UserId = int.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value);

            var todoFromRepo = await _repo.GetToDo(todoId, UserId);

            var file = photoForCreationDto.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(500).Height(500).Crop("fill").Gravity("face")
                    };

                    uploadResult = _cloudinary.Upload(uploadParams);
                }
            }

            photoForCreationDto.Url      = uploadResult.Uri.ToString();
            photoForCreationDto.PublicId = uploadResult.PublicId;

            var photo = _mapper.Map <Image>(photoForCreationDto);

            todoFromRepo.Images.Add(photo);

            if (await _repo.SaveAll())
            {
                return(Ok(todoFromRepo.Id));
            }


            return(BadRequest("Failed to add"));
        }