Exemplo n.º 1
0
        public async Task <IActionResult> UploadAvatar(string username, [FromForm] AppUserAvatarModel image)
        {
            if (string.IsNullOrEmpty(username))
            {
                return(BadRequest());
            }
            if (ActionResult(username, out var unauthorized))
            {
                return(unauthorized);
            }

            var user = await _userService.GetUserByNameAsync(username);

            if (user == null)
            {
                return(NotFound("Such user does not exists."));
            }

            var avatarUrl = await _userService.UploadAvatar(username, image);

            return(Ok(avatarUrl));
        }
Exemplo n.º 2
0
        public async Task <string> UploadAvatar(string username, AppUserAvatarModel image)
        {
            var fileName  = image.ProfileImage.FileName;
            var extension = Path.GetExtension(fileName);

            var newFileName = $"{Guid.NewGuid()}{extension}";
            var filePath    = Path.Combine(_webHostEnvironment.ContentRootPath, "wwwroot", "Avatars", newFileName);

            await using (var fileStream = new FileStream(filePath, FileMode.Create, FileAccess.Write))
            {
                await image.ProfileImage.CopyToAsync(fileStream);
            }

            var avatarUrl =
                $"{_httpContextAccessor.HttpContext.Request.Scheme}://{_httpContextAccessor.HttpContext.Request.Host.Value}/wwwroot/Avatars/{newFileName}";

            var user = await GetUserByNameAsync(username);

            user.ProfileImage = avatarUrl;

            await _dataContext.SaveChangesAsync();

            return(avatarUrl);
        }