Exemple #1
0
        public async Task <Result <string> > UploadUserImageAsync(UserImageInputModel model)
        {
            if (model?.File == null)
            {
                return(Result.Fail <string>(EC.ImageInvalid, ET.ImageInvalid));
            }

            if (model.File.Length > FileLength)
            {
                return(Result.Fail <string>(EC.LengthImageInvalid, ET.LengthImageInvalid));
            }

            var user = await _userRepository.GetUserByIdAsync(_userContext.UserId);

            if (user == null)
            {
                return(Result.Fail <string>(EC.UserNotFound, ET.UserNotFound));
            }

            await using (var stream = new MemoryStream(DecodeUrlBase64(model.CroppedImage)))
            {
                await _userPhotoRepository.PostAsync(new UserPhoto
                {
                    UserId       = _userContext.UserId,
                    OriginalName = model.File.FileName,
                    Path         = await _userPhotoStorageService.UploadFileToBlobAsync(stream, model.File.ContentType)
                });
            }

            var position = JsonSerializer.Serialize(new PositionModel
            {
                X1 = model.X1,
                X2 = model.X2,
                Y1 = model.Y1,
                Y2 = model.Y2
            });

            var path = await _userPhotoStorageService.UploadFileToBlobAsync(model.File);

            var photo = await _userPhotoRepository.GetUserPhotoById(_userContext.UserId);

            if (photo == null)
            {
                await _userPhotoRepository.PostAsync(new UserPhoto
                {
                    UserId       = _userContext.UserId,
                    OriginalName = model.File.FileName,
                    Path         = path,
                    Position     = position
                });
            }
            else
            {
                await _userPhotoStorageService.DeleteBlobDataAsync(photo.Path);

                photo.OriginalName = model.File.FileName;
                photo.Path         = path;
                photo.Position     = position;

                _userPhotoRepository.Put(photo);
            }

            await _unitOfWorks.CommitAsync();

            return(Result.OK(path));
        }