Esempio n. 1
0
        public async Task <IActionResult> UpdateAvatar([FromForm] AvatarModel model)
        {
            string fileName    = "";
            string filePath    = "";
            string newFileName = "";

            try
            {
                fileName = model.Image.GetFileName();

                var extension = Path.GetExtension(fileName);

                #region Validations

                // check for invalid characters
                if (fileName.IndexOfAny(Path.GetInvalidFileNameChars()) >= 0)
                {
                    return(BadRequest());
                }

                // file name should not exceed 255 characters
                if (fileName.Length > 255)
                {
                    return(BadRequest());
                }

                // check for valid extensions
                if (!Constants.AcceptedExtensions.Any(e => e == extension.ToUpper()))
                {
                    return(BadRequest());
                }

                // check image header bytes
                using (var sourceStream = model.Image.OpenReadStream())
                {
                    if (!ImageValidationHelper.ValidateImageHeaders(sourceStream))
                    {
                        return(BadRequest());
                    }
                }
                #endregion

                newFileName = Guid.NewGuid().ToString() + extension;
                filePath    = Path.Combine(_dynamicConfig.CacheFolder, Constants.AvatarFolder, newFileName);

                _fileUploadService.CreateDirectory(filePath);
                await _fileUploadService.CopyFile(model.Image, filePath, FileMode.Create);

                var user = await _accountService.GetUser(User.Identity.Name);

                user.AvatarImage = newFileName;
                await _accountService.SaveUser(user);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"Failed to save avatar profile image: {fileName}");
                throw;
            }

            return(Ok(new { avatarImage = newFileName }));
        }