public async Task UploadImageAsync(HomePageUserViewModel inputModel, string userId, string imagePath) { var user = this.userRepository.AllAsNoTracking().Where(x => x.Id == userId).FirstOrDefault(); Directory.CreateDirectory($"{imagePath}/users/"); var extension = Path.GetExtension(inputModel.Image.FileName).TrimStart('.'); if (!this.allowedExtensions.Any(x => extension.EndsWith(x))) { throw new Exception($"Invalid image extension {extension}"); } var newImage = new Image { AddedByUserId = userId, Extension = extension, MealId = 400, }; await this.imageRepository.AddAsync(newImage); await this.imageRepository.SaveChangesAsync(); user.Images.Add(newImage); var physicalPath = $"{imagePath}/users/{newImage.Id}.{extension}"; using var fileStream = new FileStream(physicalPath, FileMode.Create); await inputModel.Image.CopyToAsync(fileStream); await this.userRepository.SaveChangesAsync(); }
public async Task <IActionResult> UploadUserImage(HomePageUserViewModel inputModel) { var user = await this.userManager.GetUserAsync(this.User); try { await this.usersService.UploadImageAsync(inputModel, user.Id, $"{this.environment.WebRootPath}/images"); } catch (System.Exception) { return(this.Conflict()); } return(this.Redirect("/")); }
public async Task TestUploadImageAsync() { ApplicationDbContext db = GetDb(); var user = new ApplicationUser { Id = "userId", }; await db.Users.AddAsync(user); await db.SaveChangesAsync(); var userRepository = new EfDeletableEntityRepository <ApplicationUser>(db); var imageRepository = new EfRepository <Image>(db); var service = new UsersService(userRepository, imageRepository); var fileMock = new Mock <IFormFile>(); // Setup mock file using a memory stream var content = "Hello World from a Fake File"; var fileName = "test.png"; var ms = new MemoryStream(); var writer = new StreamWriter(ms); writer.Write(content); writer.Flush(); ms.Position = 0; fileMock.Setup(_ => _.OpenReadStream()).Returns(ms); fileMock.Setup(_ => _.FileName).Returns(fileName); fileMock.Setup(_ => _.Length).Returns(ms.Length); var file = fileMock.Object; var inputModel = new HomePageUserViewModel { Image = file, }; await service.UploadImageAsync(inputModel, "userId", "wwwroot/images/users"); Assert.True(db.Users.Any(x => x.Images != null)); Assert.Equal(1, db.Images.Count()); }
public async Task <IActionResult> Index() { // Move to administration area. // await this.mealScraperService.PopulateDbWithMeal(2); // await this.scraperService.PopulateDbWithExercises(2); if (this.User.Identity.IsAuthenticated) { var user = await this.userManager.GetUserAsync(this.User); var viewModel = this.usersService.GetById <HomePageUserViewModel>(user.Id); return(this.View(viewModel)); } else { var viewModel = new HomePageUserViewModel(); viewModel.RandomMeals = this.mealService.GetRandom <HomePageMealsViewModel>(3); return(this.View(viewModel)); } }