Example #1
0
        public async Task <IActionResult> ChangeImage([FromForm] UserChangeImage form, [FromServices] IServiceScopeFactory serviceScopeFactory)
        {
            if (!ModelState.IsValid)
            {
                return(Redirect("/"));
            }

            string viewerUserId = this.GetViewerUserId();

            if (form.UserId != viewerUserId)
            {
                return(Redirect("/"));
            }

            string imageUrl = string.Empty;

            await using (var memoryStream = new MemoryStream())
            {
                await form.File.CopyToAsync(memoryStream).ConfigureAwait(false);

                using var scope = serviceScopeFactory.CreateScope();
                var fileService = scope.ServiceProvider.GetService <IFileService>();

                imageUrl = await fileService.Add(FileUse.UserImage, form.UserId, form.File.ContentType, memoryStream)
                           .ConfigureAwait(false);
            }

            await _userService.SetImage(form.UserId, imageUrl);

            _logger.LogInformation("User: {UserId} has changed their image", viewerUserId);

            return(RedirectToAction("UserView", new { userId = form.UserId }));
        }
        public IActionResult ChangePhoto(UserChangeImage model)
        {
            var id = User.FindFirst(ClaimTypes.NameIdentifier)?.Value;

            model.userId = int.Parse(id);

            string uniqueFileName = null;

            if (model.uploadImage != null)
            {
                string uploadsFolder = Path.Combine(hostingEnvironment.WebRootPath, "images");
                uniqueFileName = Guid.NewGuid().ToString() + "_" + model.uploadImage.FileName;
                string filePath = Path.Combine(uploadsFolder, uniqueFileName);
                model.uploadImage.CopyTo(new FileStream(filePath, FileMode.Create));
            }

            userDatabaseRepository.changeProfilePic(uniqueFileName, model.userId);
            return(RedirectToAction("Index"));
        }