public async Task <IAsyncResult> ChangeAvatar(AvatarForChange avatarForChange) { var user = await usersRepo.GetSingleUserAsync(avatarForChange.UserId); var file = avatarForChange.File; var uploadResult = new ImageUploadResult(); if (!string.IsNullOrEmpty(user.PhotoCloudinaryPublicId) && !string.IsNullOrEmpty(user.PhotoUrl) && file.Length > 0) { var deleteParams = new DeletionParams(user.PhotoCloudinaryPublicId); var result = await cloudinary.DestroyAsync(deleteParams); if (result.Result == "ok") { user.PhotoUrl = string.Empty; user.PhotoCloudinaryPublicId = string.Empty; } else { throw new Exception("Przy zmianie zdjęcia wystąpił bląd."); } } var photoId = user.Id + "_main"; if (file.Length > 0) { using (var stream = file.OpenReadStream()) { var uploadParams = new ImageUploadParams() { File = new FileDescription(file.Name, stream), Transformation = new Transformation() .Width(500).Height(500).Crop("fill").Gravity("face"), PublicId = photoId }; uploadResult = cloudinary.Upload(uploadParams); } } user.PhotoUrl = uploadResult.Url.ToString(); user.PhotoCloudinaryPublicId = uploadResult.PublicId; if (await usersRepo.SaveAllAsync()) { return(Task.CompletedTask); } throw new Exception("Coś poszło nie tak :("); }
public async Task <IActionResult> ChangeAvatar([FromForm] AvatarForChange avatarForChange) { try { var myID = int.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value); avatarForChange.UserId = myID; await usersService.ChangeAvatar(avatarForChange); return(NoContent()); } catch (Exception e) { return(BadRequest(e.Message)); } }