コード例 #1
0
        public async Task <IActionResult> AddPhotoForUser(int userId,
                                                          [FromForm] PhotoForCreationDto photoForCreationDto)
        {
            //if (userId != int.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value))
            //    return Unauthorized();

            var userFromRepo = await _repo.GetUser(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 <Photo>(photoForCreationDto);

            userFromRepo.Photo = photo;


            if (await _repo.SaveAll())
            {
                var photoToReturn = _mapper.Map <PhotoForReturnDto>(photo);
                return(CreatedAtRoute("GetPhoto", new { id = photo.Id }, photoToReturn));
            }

            return(BadRequest("Could not add the photo"));
        }
コード例 #2
0
        public async Task <IActionResult> AddPhotoForProperty(int propertyId, [FromForm] PhotoForCreationDto photoForCreationDto)
        {
            var propertyFromRepo = await _repo.GetProperty(propertyId);

            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 <Photo>(photoForCreationDto);

            if (!propertyFromRepo.Photos.Any(p => p.isMain))
            {
                photo.isMain = true;
            }

            propertyFromRepo.Photos.Add(photo);

            if (await _repo.SaveAll())
            {
                var photoToReturn = _mapper.Map <PhotoForReturnDto>(photo);
                return(CreatedAtRoute("GetPhoto", new { propertyId = propertyId, id = photo.Id }, photoToReturn));
            }
            return(BadRequest("Cound not add the photo"));
        }
コード例 #3
0
        public async Task <IActionResult> AddPhotoForListing(int listingId, [FromForm] PhotoForCreationDto photoForCreationDto)
        {
            var listingfromrepo = await _repo.GetListing(listingId);

            var file          = photoForCreationDto.File;
            var uploadResults = 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")
                    };
                    uploadResults = _cloudinary.Upload(uploadParams);
                }
            }

            photoForCreationDto.PhotoUrl = uploadResults.Uri.ToString();
            photoForCreationDto.PublicId = uploadResults.PublicId;

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

            if (!listingfromrepo.Photos.Any(u => u.IsMain))
            {
                photo.IsMain = true;
            }
            if (listingfromrepo.Photos.Count == 0)
            {
                listingfromrepo.PhotoUrl = photo.PhotoUrl;
            }

            listingfromrepo.Photos.Add(photo);

            if (await _repo.SaveAll())
            {
                var photoToReturn = _mapper.Map <PhotoForReturnDto>(photo);
                return(CreatedAtRoute("GetPhoto", new { id = photo.Id }, photoToReturn));
            }
            return(BadRequest("Could not add photo"));
        }
コード例 #4
0
        public async Task <IActionResult> AddPhotoForClient(int clientId
                                                            , [FromForm] PhotoForCreationDto photoForCreationDto)
        {
            if (clientId != int.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value))
            {
                return(Unauthorized());
            }

            var clientFromRepo = await _repo.GetClient(clientId);

            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(350).Height(350).Crop("fill")
                    };

                    uploadResult = _cloudinary.Upload(uploadParams);
                }
            }

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

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

            clientFromRepo.ClientImages.Add(photo);

            if (await _repo.SaveAll())
            {
                var photoToReturn = _mapper.Map <PhotoForReturnDto>(photo);
                return(CreatedAtRoute("GetPhoto", new { id = photo.Id }, photoToReturn));
            }
            return(BadRequest("사진 업로드에 실패하였습니다."));
        }
コード例 #5
0
        public async Task <IActionResult> AddUserPhoto(int userId, [FromForm] PhotoForCreationDto photoForCreationDto)
        {
            if (userId != int.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value))
            {
                return(Unauthorized());
            }

            var userFromRepo = await _repo.GetUser(userId);

            var file         = photoForCreationDto.File;
            var uploadResult = new ImageUploadResult();

            using (var stream = file.OpenReadStream())
            {
                var uploadParam = new ImageUploadParams()
                {
                    File           = new FileDescription(file.FileName, stream),
                    Transformation = new Transformation().Width(500).Height(500).Crop("fill").Gravity("face")
                };
                uploadResult = _cloudinary.Upload(uploadParam);
            }
            photoForCreationDto.Url      = uploadResult.Uri.ToString();
            photoForCreationDto.publicId = uploadResult.PublicId;

            var photo = _autoMapper.Map <Photo>(photoForCreationDto);

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

            userFromRepo.Photos.Add(photo);

            if (await _repo.SaveAll())
            {
                var photoFromRepo = await _repo.GetPhotos(photo.Id);

                var photoToReturn = _autoMapper.Map <PhotoForReturnDto>(photoFromRepo);
                return(Ok(photoToReturn));
            }
            return(BadRequest("Error in Uploading Photo"));
        }
コード例 #6
0
        public async Task <IActionResult> AddPhotoForBike(int bikeId, [FromForm] PhotoForCreationDto photoForCreationDto)
        {
            var bikeFromRepo = await _bikeRepo.GetBike(bikeId);

            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),
                        Folder = "AperoApp"
                    };

                    uploadResult = _cloudinary.Upload(uploadParams);
                }
            }

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

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

            if (!bikeFromRepo.Photos.Any(u => u.IsMain))
            {
                photo.IsMain = true;
            }

            bikeFromRepo.Photos.Add(photo);

            if (await _bikeRepo.SaveAll())
            {
                var photoToReturn = _mapper.Map <PhotoForReturnDto>(photo);
                return(CreatedAtRoute("GetPhoto", new { bikeId = bikeId, id = photo.Id }, photoToReturn));
            }

            return(BadRequest("Could not add the photo"));
        }
        public async Task <IActionResult> AddPhotoForLocation(int photoId, [FromForm] PhotoForCreationDto photoForCreationDto)
        {
            var locationFromRepo = await _repo.GetLocation(photoId);

            if (locationFromRepo == null)
            {
                return(NoContent());
            }

            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(590).Height(590).Crop("fill")
                    };

                    uploadResult = _cloudinary.Upload(uploadParams);
                }
            }

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

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

            locationFromRepo.Photos.Add(photo);

            if (await _repo.SaveAll())
            {
                var photoToReturn = _mapper.Map <PhotoToReturnDto>(photo);
                return(CreatedAtRoute("GetPhoto", new { photoId = photo.Id }, photoToReturn));
            }

            return(BadRequest("Could not add photo"));
        }
コード例 #8
0
        public async Task <IActionResult> AddedPhotoForValue(int valueId, [FromForm] PhotoForCreationDto photoForCreation)
        {
            var value = await repository.GetValue(valueId);

            var file         = photoForCreation.File;
            var uploadResult = new ImageUploadResult();

            if (file.Length > 0)
            {
                using (var stream = file.OpenReadStream())
                {
                    var uploadParams = new ImageUploadParams()
                    {
                        File = new FileDescription(file.Name, stream)
                    };

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

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

            var photo = mapper.Map <Photo>(photoForCreation);

            if (!value.Photos.Any(p => p.IsMain))
            {
                photo.IsMain = true;
            }

            value.Photos.Add(photo);

            if (await repository.SaveAll())
            {
                var photoForReturn = mapper.Map <PhotoForReturnDto>(photo);
                return(CreatedAtRoute("GetPhoto", new { id = photo.Id }, photoForReturn));
            }


            return(BadRequest("Nie udało się dodać zdjęcia"));
        }
コード例 #9
0
        public async Task <IActionResult> AddPhotoForUser(int userId,
                                                          [FromForm] PhotoForCreationDto photoForCreationDto)
        {
            if (userId != Int32.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value))
            {
                return(Unauthorized());
            }
            var userFromRepo = await _repo.GetUser(userId);

            var file         = photoForCreationDto.File;
            var uploadResult = new ImageUploadResult();//cloudnary object to store image result

            if (file.Length > 0)
            {
                using (var stream = file.OpenReadStream()){
                    var imageUploadParam = new ImageUploadParams()
                    {
                        File           = new FileDescription(file.Name, stream),
                        Transformation = new Transformation().Width(500).Height(500).Crop("fill").Gravity("face")
                    };
                    uploadResult = _cloudinary.Upload(imageUploadParam);
                }
            }
            photoForCreationDto.Url      = uploadResult.Url.ToString();
            photoForCreationDto.PublicId = uploadResult.PublicId;
            var photo = _mapper.Map <Photo>(photoForCreationDto);

            //setting photo as Main if we dont have any main photo or if its first photo
            if (!userFromRepo.Photos.Any(u => u.IsMain))
            {
                photo.IsMain = true;
            }
            userFromRepo.Photos.Add(photo);
            if (await _repo.SaveAll())
            {
                var photoForReturnDto = _mapper.Map <PhotoForReturnDto>(photo);//we will get id generated after storing
                //so we save photoForReturnDto(to get id) after we id in photo
                return(CreatedAtRoute("GetPhoto", new { id = photo.Id, userId = userId }, photoForReturnDto));
            }
            return(BadRequest("we are unable tosave photo"));
        }
コード例 #10
0
        public async Task <IActionResult> AddPhotoForUser(int userId, [FromForm] PhotoForCreationDto photoDto)
        {
            if (userId != int.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value))
            {
                return(Unauthorized());
            }

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

            var file         = photoDto.file;
            var uploadResult = new ImageUploadResult();

            if (file.Length > 0)
            {
                using (var fileStream = file.OpenReadStream()) {
                    var uploadParams = new ImageUploadParams {
                        File           = new FileDescription(file.Name, fileStream),
                        Transformation = new Transformation().Width(500).Height(500).Crop("fill").Gravity("face")
                    };
                    uploadResult = _cloudinary.Upload(uploadParams);
                }
            }
            photoDto.Url      = uploadResult.Url.ToString();
            photoDto.PublicId = uploadResult.PublicId;
            var photo = _mapper.Map <Photo>(photoDto);

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

            userFromRepo.Photos.Add(photo);

            if (await _repository.SaveAll())
            {
                var photoToReturn = _mapper.Map <PhotoforReturnDto>(photo);  // since save is successful .. we will have id created.
                return(CreatedAtRoute("GetPhoto", new { userId = userId, id = photo.Id }, photoToReturn));
            }

            throw new System.Exception("Photo upload Failed!");
        }
コード例 #11
0
        public async Task <IActionResult> AddPhotoForUser(int userid, [FromForm] PhotoForCreationDto photoforcreation)
        {
            if (userid != int.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value))
            {
                return(Unauthorized());
            }

            var user = await _repository.GetUser(userid);

            var file         = photoforcreation.File;
            var uploadResult = new ImageUploadResult();

            if (file.Length > 0)
            {
                using (var stream = file.OpenReadStream()) {
                    var imageParams = new ImageUploadParams()
                    {
                        File           = new FileDescription(file.Name, stream),
                        Transformation = new Transformation().Width(500).Height(500).Crop("fill").Gravity("face"),
                    };
                    uploadResult = _cloudinary.Upload(imageParams);
                }
            }
            photoforcreation.Url      = uploadResult.Uri.ToString();
            photoforcreation.PublicId = uploadResult.PublicId;

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

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

            user.Photos.Add(photo);
            if (await _repository.SaveAll())
            {
                var photoForReturn = _mapper.Map <PhotoForReturnDto>(photo);
                return(CreatedAtRoute("GetPhoto", new { userid = userid, id = photo.Id }, photoForReturn));
            }
            return(BadRequest("Exception occured while uploading the image"));
        }
コード例 #12
0
        public async Task <IActionResult> AddPhotoForUser(int userId, PhotoForCreationDto photoForCreationDto)
        {
            if (userId != int.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value))
            {
                return(Unauthorized());
            }

            var userForRepo = await repo.GetUser(userId);

            var file = photoForCreationDto.FormFile;

            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 <Photo>(photoForCreationDto);

            if (!userForRepo.Photos.Any(p => p.IsMain))
            {
                photo.IsMain = true;
            }

            userForRepo.Photos.Add(photo);
        }
コード例 #13
0
        public async Task <PhotoForReturnDto> AddPhotoUser(int userId, PhotoForCreationDto photoForCreationDto)
        {
            var user = await _dataContext.GetUser(userId, true);

            var uploadResult = new ImageUploadResult();
            var file         = photoForCreationDto.File;

            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 <Photo>(photoForCreationDto);

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

            user.Photos.Add(photo);

            if (await _dataContext.SaveAll())
            {
                return(_mapper.Map <PhotoForReturnDto>(photo));
            }

            return(null);
        }
コード例 #14
0
        public async Task <IActionResult> AddPhotoForUser(int userId,
                                                          [FromForm] PhotoForCreationDto photoForCreationDto)
        {
            if (userId != int.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value))
            {
                return(Unauthorized());
            }

            var userFromRepo = await _usersService.GetUser(userId);

            _photosService.UploadPhotoToCloudinary(photoForCreationDto.File, photoForCreationDto);

            var photo = _photosService.MapUploadedPhoto(photoForCreationDto, userFromRepo);

            if (await _usersService.SaveChangesInContext())
            {
                var photoToReturn = _photosService.MapPhotoForReturn(photo);
                return(CreatedAtRoute("GetPhoto", new { userId, id = photo.Id }, photoToReturn));
            }

            return(BadRequest("Could not add the photo"));
        }
コード例 #15
0
        private async Task <ActionResult> AddPhotoToUser(AppUser user, PhotoForCreationDto photoDto)
        {
            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(600).Height(600).Crop("fit")
                    };

                    uploadResult = _cloudinary.Upload(uploadParams);
                }
            }

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

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

            photo.AppUserId = user.Id;
            _repo.Add(photo);
            // if(user.MainPhotoUrl == null){
            //     user.MainPhotoUrl = photoDto.Url;
            // }

            if (await _repo.SaveAll() > 0)
            {
                var photoToReturn = _mapper.Map <PhotoForReturnDto>(photo);
                return(CreatedAtRoute("GetPhoto", new { id = photo.Id }, photoToReturn));
            }

            return(BadRequest("Could not add the photo"));
        }
コード例 #16
0
        public void Given_ProductIdAndPhotoForCreation_When_AddPhotoForProduct_CaseWhenProductAlreadyHaveMainPhoto_ThenVerifyIfPhotoWasntSetAsMain()
        {
            //Arrange

            int productId           = 1;
            var photoForCreationDto = new PhotoForCreationDto()
            {
                File = _mockedFormFile.Object
            };
            var productPhotoList = new List <Photo>()
            {
                new Photo()
                {
                    isMain = true
                }
            };

            _mockedUnitOfWork.Setup(s => s.Product.GetWithPhotosOnly(productId))
            .ReturnsAsync(new Product()
            {
                Photos = productPhotoList
            });

            _mockedAddPhotoToCloud.Setup(s => s.Do(It.IsAny <Cloudinary>(), photoForCreationDto)).Returns(true);

            _mockedUnitOfWork.Setup(s => s.SaveAsync()).ReturnsAsync(true);


            //Act
            var result = _cut.AddPhotoForProduct(productId, photoForCreationDto).Result;

            //Assert
            result.Should().BeOfType <CreatedAtRouteResult>();
            result.As <CreatedAtRouteResult>().Value.As <PhotoForReturnDto>().isMain.Should().BeFalse();

            _mockedUnitOfWork.Verify(v => v.Product.GetWithPhotosOnly(productId), Times.Once);
            _mockedUnitOfWork.Verify(v => v.SaveAsync(), Times.Once);
        }
コード例 #17
0
        public async Task <IActionResult> AddPhotoForUser([FromBody] PhotoForCreationDto photoForCreationDto)
        {
            try
            {
                var currentUser = await _datingRepository.GetUser(photoForCreationDto.UserId);

                if (currentUser == null)
                {
                    return(BadRequest("User not found"));
                }
                string webRootPath = @"C:\Users\emrah\source\repos\Demo\DatingApp\DatingApp.API\WebImages\Upload";
                AmazonUploader.AmazonS3Uploader.keyName  = photoForCreationDto.FileName;
                AmazonUploader.AmazonS3Uploader.filePath = webRootPath;
                var result = await AmazonUploader.AmazonS3Uploader.UploadFileAsync();

                photoForCreationDto.Url = "https://barstechcloudtestbucket2019.s3.amazonaws.com/" + photoForCreationDto.FileName;

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

                if (!photo.IsMain)
                {
                    photo.IsMain = true;
                }
                currentUser.Photos.Add(photo);

                var photoToReturn = _mapper.Map <PhotoForReturnDto>(photo);
                if (await _datingRepository.SaveAll())
                {
                    return(CreatedAtRoute("GetPhoto", new { id = photo.Id }, photoToReturn));
                }

                return(BadRequest("Phot could not added to AWS s3 service..."));
            }
            catch (Exception ex)
            {
                return(BadRequest("Phot could not added to AWS s3 service...Message :" + ex.Message));
            }
        }
コード例 #18
0
ファイル: PhotoService.cs プロジェクト: jdready66/DatingApp
        public ImageUploadResult UploadPhoto(PhotoForCreationDto photoForCreationDto)
        {
            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);
                }
            }

            return(uploadResult);
        }
コード例 #19
0
        private void InitializeObjects()
        {
            _service = new PhotoService(_cloudUploadService.Object, _mapper.Object, _uow.Object);

            _photoForCreation = new PhotoForCreationDto
            {
                File         = new Mock <IFormFile>().Object,
                Description  = "description",
                EntityTypeId = (int)EntityTypes.Film,
                EntityId     = 1
            };

            _uploadResult = new PhotoCloudUploadResult
            {
                PublicId = "PublicId",
                Url      = "Url"
            };

            _photo = new Domain.Entities.Photo();

            _mainPhoto = new Domain.Entities.Photo();

            _photos = new List <Domain.Entities.Photo>();

            _photosForDetailed = new List <PhotoForDetailedDto>
            {
                new PhotoForDetailedDto {
                },
                new PhotoForDetailedDto {
                }
            };

            _mainPhotoUploadable = new MainPhotoUploadable
            {
                Id = 1
            };
        }
コード例 #20
0
        public ActionResult AddPhotoForCity([FromForm] PhotoForCreationDto photoForCreationDto)
        {
            /*
             * var currentUserId = int.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value);
             *
             * if (currentUserId == null)
             * {
             *  return Unauthorized();
             * }
             */
            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)
                    };

                    uploadResult = _cloudinary.Upload(uploadParams);
                }
            }

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

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

            _photoRepository.Add(photo);
            _photoRepository.SaveAll();
            return(Ok(photo));
        }
コード例 #21
0
        public async Task <IActionResult> AddPhotoForUser(int userid, [FromForm] PhotoForCreationDto photoForCreationDto)
        {
            var userFromRepo = await _repo.GetUser(userid, true);

            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 <Photo>(photoForCreationDto);

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

            userFromRepo.Photos.Add(photo);
            if (await _repo.SaveAll())
            {
                var photoToReturn = _mapper.Map <PhotoForReturnDto>(photo);
                return(CreatedAtRoute("GetPhoto", new { id = photo.Id }, photoToReturn));
            }
            return(BadRequest("BRHA PHOTO NOT ADDED"));
        }
コード例 #22
0
        public async Task <IActionResult> AddPhotoForProduct(int productId,
                                                             [FromForm] PhotoForCreationDto photoForCreationDto)
        {
            var productFromRepo = await _unitOfWork.Product.GetWithPhotosOnly(productId);


            var file = photoForCreationDto.File;

            if (file == null)
            {
                return(BadRequest("Photo file wasn't sent"));
            }

            if (!_addPhotoToCloud.Do(_cloudinary, photoForCreationDto))
            {
                return(BadRequest("File wasn't saved in cloud"));
            }

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

            if (!productFromRepo.Photos.Any(p => p.isMain))
            {
                photo.isMain = true;
            }

            productFromRepo.Photos.Add(photo);



            if (await _unitOfWork.SaveAsync())
            {
                var photoToReturn = _mapper.Map <PhotoForReturnDto>(photo);
                return(CreatedAtRoute("GetPhoto", new { productId = productId, id = photo.Id }, photoToReturn));
            }

            return(BadRequest($"Could not add photo for product: {productId}"));
        }
コード例 #23
0
        public async Task <IActionResult> AddPhotoForAutomotive(int serviceId, [FromForm] PhotoForCreationDto photoForCreationDto)
        {
            var serviceFromRepo = await _repo.GetService(serviceId);

            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("lfill")
                    };

                    uploadResult = _cloudinary.Upload(uploadParams);
                }
            }

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

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

            serviceFromRepo.Photo = photo;

            if (await _repo.SaveAll())
            {
                var photoToReturn = _mapper.Map <PhotoForReturnDto>(photo);
                return(CreatedAtRoute("GetServicePhoto", new { id = photo.Id }, photoToReturn));
            }

            return(BadRequest("Could not add the photo"));
        }
コード例 #24
0
ファイル: PhotosController.cs プロジェクト: panta97/ImageAPI
        public async Task <IActionResult> AddPhotoForUser(PhotoForCreationDto photoDto)
        {
            // Upload the photo to cloudinary
            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),
                    };

                    uploadResult = _cloudinary.Upload(uploadParams);
                }
            }

            // If everything goes well then get the url's photo to storage on the database
            photoDto.Url      = uploadResult.Uri.ToString();
            photoDto.PublicId = uploadResult.PublicId;

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

            _repo.Add(photo);

            if (await _repo.SaveAll())
            {
                var photoToReturn = _mapper.Map <PhotoForReturnDto>(photo);
                return(CreatedAtRoute("GetPhoto", new { id = photo.Id }, photoToReturn));
            }

            return(BadRequest("Could not add the photo"));
        }
コード例 #25
0
        public async Task <IActionResult> AddPhotoToNewOffer(int userId,
                                                             [FromForm] PhotoForCreationDto photoForCreationDto,
                                                             [FromForm] OfferForRegisterDto offerForRegisterDto)
        {
            if (userId != int.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value))
            {
                return(Unauthorized());
            }

            Photo photo = UploadPhotoToCloudinary(photoForCreationDto);

            photo.IsMain = true;

            Offer offer = await _repo.GetOfferById(offerForRegisterDto.Id);

            if (offer == null)
            {
                offer = _mapper.Map <Offer>(offerForRegisterDto);
                offer.Photos.Add(photo);
                _repo.Add(offer);
            }
            else
            {
                offer.Photos.Add(photo);
                _repo.Update(offer);
            }

            if (await _repo.SaveAllAsync())
            {
                var offerForReturnDto = _mapper.Map <OfferForReturnDto>(offer);

                return(CreatedAtRoute("GetOfferById", new { controller = "ofertas", id = offerForReturnDto.Id }, offerForReturnDto));
            }

            return(BadRequest("Could not add the photo"));
        }
コード例 #26
0
        public async Task <PhotoToReturnDto> UploadPhoto(int userId, PhotoForCreationDto photoForCreationDto)
        {
            var image = photoForCreationDto.File;

            if (ImageValidator.ImageExtensionValidation(image.FileName) &&
                ImageValidator.ImageSizeValidation(image.Length) &&
                ImageValidator.ImageSignatureValidation(image))
            {
                using (var memoryStream = new MemoryStream())
                {
                    await photoForCreationDto.File.CopyToAsync(memoryStream);

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

                    photo.Image  = memoryStream.ToArray();
                    photo.UserId = userId;

                    // Check if photo that is going to be uploaded is main profile photo
                    // If it is, we have to find current main photo, and change it to not be main
                    var currentMainPhoto = await _unitOfWork.Photos.GetMainPhotoForUser(userId);

                    if (photo.IsMain && currentMainPhoto != null)
                    {
                        currentMainPhoto.IsMain = false;
                    }
                    _unitOfWork.Photos.Add(photo);

                    if (await _unitOfWork.Complete())
                    {
                        return(_mapper.Map <PhotoToReturnDto>(photo));
                    }
                }
            }

            return(null);
        }
コード例 #27
0
        public IActionResult AddPhotoForCity(int cityId, [FromForm] PhotoForCreationDto photoForCreationDto)
        {
            var city = _cityService.GetCityById(cityId).Data;

            if (city == null)
            {
                return(BadRequest("Could not find city"));
            }
            var currentUserId = int.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value);

            if (currentUserId != city.UserId)
            {
                return(Unauthorized());
            }

            var file = photoForCreationDto.Files;

            try
            {
                var uploadResult = new ImageUploadResult();
                if (file.Length > 0)
                {
                    using (var stream = file.OpenReadStream())
                    {
                        var uploadParam = new ImageUploadParams
                        {
                            File = new FileDescription(file.Name, stream)
                        };

                        uploadResult = _cloudinary.Upload(uploadParam);
                    };

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

                    var photo = _mapper.Map <Photo>(photoForCreationDto);
                    photo.CityId = city.Id;

                    if (!city.Photos.Any(p => p.IsMain))
                    {
                        photo.IsMain = true;
                    }

                    var photoDbResult = _photoService.AddPhotoForCity(photo);

                    if (photoDbResult.Success)
                    {
                        var photoToReturn = _mapper.Map <PhotoForReturnDto>(photo);
                        return(Ok(photoToReturn));
                    }
                    return(BadRequest("Could not add the photo"));
                }
            }

            catch (Exception ex)
            {
                return(BadRequest(ex.Message.ToString()));
            }

            return(BadRequest("Failed"));
        }
コード例 #28
0
        public async Task <IActionResult> AddPhoto([FromForm] PhotoForCreationDto photoDto)
        {
            var photo = await _service.UploadPhoto(base.GetUserIdFromToken(), photoDto);

            return(Ok(_mapper.To <PhotoToReturnDto>(photo)));
        }
コード例 #29
0
        public async Task <IActionResult> AddPhoto(bool photoStatusApproved, string userId, Guid classifiedAdId,
                                                   [FromForm] PhotoForCreationDto photoForCreationDto)
        {
            var user = await _userManager.Users.SingleOrDefaultAsync(x => x.Id == userId);

            if (user == null)
            {
                return(Unauthorized());
            }

            var classifiedAdFromRepo = await _classifiedAdsRepo.GetClassifiedAdDetailAndPhotos(classifiedAdId);

            var file = photoForCreationDto.File;

            var uploadResult = new ImageUploadResult();

            if (file.Length > 0)
            {
                /*using (var stream = file.OpenReadStream())
                 * {*/
                //var filePath = Path.Combine(Directory.GetCurrentDirectory(), @"wwwroot\images", userId, classifiedAdId.ToString(), new Guid().ToString());
                //Getting FileName
                var fileName = ContentDispositionHeaderValue.Parse(file.ContentDisposition).FileName.Trim('"');

                //Assigning Unique Filename (Guid)
                var myUniqueFileName = Convert.ToString(Guid.NewGuid());

                //Getting file Extension
                var FileExtension = Path.GetExtension(fileName);

                // concating  FileName + FileExtension
                var newFileName = myUniqueFileName + FileExtension;

                // Combines two strings into a path.
                fileName = Path.Combine(_environment.WebRootPath, "images", userId, classifiedAdId.ToString()) + $@"\{newFileName}";

                // if you want to store path of folder in database
                var UrlWithoutHost = "images/" + userId + "/" + classifiedAdId.ToString() + "/" + newFileName;
                if (Directory.Exists(Path.Combine(_environment.WebRootPath, "images", userId, classifiedAdId.ToString())))
                {
                    Console.WriteLine("That path exists already.");
                    // return;
                }
                else
                {
                    DirectoryInfo directory = Directory.CreateDirectory(Path.Combine(_environment.WebRootPath, "images", userId, classifiedAdId.ToString()));
                }
                // Try to create the directory.

                using (FileStream fs = System.IO.File.Create(fileName))
                {
                    file.CopyTo(fs);
                    fs.Flush();
                }
                UriBuilder uriBuilder = new UriBuilder();
                uriBuilder.Scheme = Request.Scheme;
                uriBuilder.Host   = Request.Host.Host;
                //uriBuilder.Path = Request.Path.ToString();
                //uriBuilder.Query = Request.QueryString.ToString();

                photoForCreationDto.Url = uriBuilder.Uri.ToString() + UrlWithoutHost;

                photoForCreationDto.PublicId = uriBuilder.Uri.ToString() + UrlWithoutHost;

                /*var uploadParams = new ImageUploadParams()
                 * {
                 *  File = new FileDescription(file.FileName, stream),
                 *  Transformation = new Transformation().Quality("auto").FetchFormat("auto").Width("auto").Dpr("auto").Crop("scale")
                 * };*/

                //uploadResult = _cloudinary.Upload(uploadParams);
                /*}*/
            }

            /*photoForCreationDto.Url = uploadResult.Url.ToString();
             * photoForCreationDto.PublicId = uploadResult.PublicId;*/

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

            if (photoStatusApproved)
            {
                photo.Status = "Approved";
            }
            else if (!photoStatusApproved)
            {
                photo.Status = "Pending";
            }


            if (!classifiedAdFromRepo.Photos.Any(p => p.IsMain))
            {
                photo.IsMain = true;
            }

            classifiedAdFromRepo.Photos.Add(photo);

            if (await _classifiedAdsRepo.SaveAll())
            {
                var photoToReturn = _mapper.Map <PhotoForReturnDto>(photo);
                return(CreatedAtRoute("GetPhoto", new { userId, id = photo.Id }, photoToReturn));
            }

            //return BadRequest("Could not add the photo");
            return(BadRequest("Грешка при додавање на сликата"));
        }
コード例 #30
0
 public async Task <IActionResult> AddPhotoForUser(int userId, PhotoForCreationDto photoForCreationDto)
 {
 }