Exemple #1
0
            public async Task <PhotoDto> Handle(Command request, CancellationToken cancellationToken)
            {
                var photoUploadResult = _photoStorage.AddPhoto(request.File);

                var user = await _context.Users
                           .Include(u => u.Photos)
                           .SingleOrDefaultAsync(u => u.UserName == _userAccessor.GetCurrentUsername());

                var photo = new Photo
                {
                    Url = photoUploadResult.Url,
                    Id  = photoUploadResult.PublicId
                };

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

                user.Photos.Add(photo);

                var success = await _context.SaveChangesAsync() > 0;

                if (success)
                {
                    return(_mapper.Map <Photo, PhotoDto>(photo));
                }

                throw new Exception("Problem saving changes");
            }
        public async Task <ActionResult <PhotoDto> > Add(int vehicleId, [FromForm] IFormFile file)
        {
            var vehicle = await _vehicleRepository.Details(vehicleId, includeRelated : false);

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

            if (file == null)
            {
                return(BadRequest("Null file"));
            }
            if (file.Length == 0)
            {
                return(BadRequest("Empty file"));
            }
            if (file.Length > _photoSettings.MaxBytes)
            {
                return(BadRequest("Max file size exceeded"));
            }
            if (!_photoSettings.IsSupported(file.FileName))
            {
                return(BadRequest("Invalid file type."));
            }

            var photoUploadResult = await _photoStorage.AddPhoto(file);

            var photo = new Photo
            {
                Id  = photoUploadResult.PublicId,
                Url = photoUploadResult.Url
            };

            vehicle.Photos.Add(photo);
            await _unitOfWork.CompleteAsync();

            return(Mapper.Map <Photo, PhotoDto>(photo));
        }