Пример #1
0
        public IActionResult UploadFile(FileToUploadDto fileToUploadDto)
        {
            try
            {
                _photoService.UploadFile(fileToUploadDto, Guid.Parse(User.Identity.Name));

                var responseString = "Photo was added successfully.";

                return(Ok(new { responseString }));
            }
            catch (InvalidOperationException invalidOperationException)
            {
                return(BadRequest(new { invalidOperationException.Message }));
            }
            catch (Exception exeption)
            {
                return(new ObjectResult(new
                {
                    Error = exeption.Message
                })
                {
                    StatusCode = StatusCodes.Status500InternalServerError
                });
            }
        }
Пример #2
0
        /// <summary>
        /// Upload image to the system.
        /// </summary>
        /// <param name="fileToUploadDto">Object of type <see cref="FileToUploadDto"/>.</param>
        /// <param name="userId"><see cref="Guid"/> user id.</param>
        /// <exception cref="InvalidOperationException">Thrown when user with this id isn`t created or cannot save changes in database.</exception>
        public void UploadFile(FileToUploadDto fileToUploadDto, Guid userId)
        {
            try
            {
                var firstIndex = fileToUploadDto.Content.IndexOf(',');
                fileToUploadDto.Content = fileToUploadDto.Content.Substring(firstIndex + 1, fileToUploadDto.Content.Length - firstIndex - 1);

                string directoryPath = $"..\\pictures\\{userId}";

                if (!_authService.UserExists(userId))
                {
                    throw new InvalidOperationException("User with this id isn`t created.");
                }

                if (!Directory.Exists(directoryPath))
                {
                    Directory.CreateDirectory(directoryPath);
                }

                string extension = Path.GetExtension(fileToUploadDto.FileName);

                Photo photoToAdd = new Photo();
                photoToAdd.Id = Guid.NewGuid();

                var fileName = photoToAdd.Id;

                photoToAdd.Description = fileToUploadDto.Description;

                photoToAdd.Path = $"{directoryPath}\\{fileName}{extension}";

                photoToAdd.UserId = userId;
                using (FileStream fileStream = new FileStream($"{directoryPath}\\{fileName}{extension}", FileMode.OpenOrCreate))
                {
                    var fileContent = Convert.FromBase64String(fileToUploadDto.Content);
                    fileStream.Write(fileContent);
                    fileStream.Flush();
                }

                _dataService.Add <Photo>(photoToAdd);

                if (!_dataService.SaveAll())
                {
                    throw new InvalidOperationException("Cannot save changes in database.");
                }
            }
            catch (InvalidOperationException invalidOperationException)
            {
                throw invalidOperationException;
            }
        }
        public void UploadPhoto_ThrowException()
        {
            var authServiceMock = new Mock <IAuthService>();
            var dataServiceMock = new Mock <IDataService>();

            Guid userId = Guid.NewGuid();

            var fileToUploadDto = new FileToUploadDto()
            {
                FileName = "newPhoto.jpg", Description = "New photo.", Content = "base64Format"
            };

            authServiceMock.Setup(u => u.UserExists(userId)).Returns(true);
            dataServiceMock.Setup(u => u.SaveAll()).Throws(new Exception("Cannot save changes in database."));

            var controller = new PhotosController(dataServiceMock.Object, authServiceMock.Object);

            var context = new ControllerContext()
            {
                HttpContext = new DefaultHttpContext
                {
                    User = new ClaimsPrincipal(new ClaimsIdentity(new List <Claim>
                    {
                        new Claim(ClaimTypes.Name, userId.ToString())
                    }, "Bearer"))
                }
            };

            controller.ControllerContext = context;

            var result = controller.UploadFile(fileToUploadDto);

            var statusCode = ((ObjectResult)result).StatusCode;
            var jsonValue  = JsonConvert.SerializeObject(((ObjectResult)result).Value);
            var dictionary = JsonConvert.DeserializeObject <Dictionary <object, object> >(jsonValue);

            Assert.True(statusCode == 500);
            Assert.Equal("Cannot save changes in database.", dictionary["Error"]);

            authServiceMock.VerifyAll();
            dataServiceMock.VerifyAll();
        }