public async Task <IActionResult> AddPhotoForAnnouncement(Guid announcementId, [FromForm] PhotoForCreation photoForCreation) { var announcementFromRepo = await _announcementService.GetAnnouncementById(announcementId); if (announcementFromRepo == null) { return(BadRequest("Invalid Request")); } if (announcementFromRepo.PostedById != User.FindFirst(ClaimTypes.NameIdentifier).Value) { return(Unauthorized()); } var photoToReturn = await _announcementService.AddPhotoForAnnouncement(announcementFromRepo, photoForCreation); if (photoToReturn != null) { return(CreatedAtRoute( routeName: "GetPhoto", routeValues: new { announcementId = announcementFromRepo.Id, id = photoToReturn.Id }, value: photoToReturn)); } return(BadRequest("Could not add the photo")); }
public async Task <IActionResult> AddSlide([FromForm] PhotoForCreation photoForCreation) { var file = photoForCreation.File; var uploadResult = new ImageUploadResult(); if (file.Length > 0) { using (var stream = file.OpenReadStream()) { var uploadParams = new ImageUploadParams() { File = new FileDescription(file.Name, stream), Folder = "shop/carousel" }; uploadResult = this.cloudinary.Upload(uploadParams); }; photoForCreation.Url = uploadResult.Uri.ToString(); photoForCreation.PublicId = uploadResult.PublicId; var slide = this.mapper.Map <Carousel>(photoForCreation); this.unitOfWork.Add(slide); if (await this.unitOfWork.CompleteAsync()) { return(Ok(slide)); } } return(BadRequest("Could not add the photo")); }
public async Task <IActionResult> AddPhotoForUser(int userId, PhotoForCreation photoDto) { var user = await _userService.GetUser(userId); if (user == null) { return(BadRequest("Could not find user")); } var currentUserId = int.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value); if (currentUserId != user.Id) { return(Unauthorized()); } var photoForReturn = await _photoService.AddPhotoForUser(userId, photoDto); if (photoForReturn != null) { return(CreatedAtRoute("GetPhoto", new { id = photoForReturn.Id }, photoForReturn)); } return(BadRequest()); }
public async Task <string> AddPhotoForProduct(int productId, PhotoForCreation photoDto) { Photo photo; var product = await _db // 1. .Products .Where(u => u.Id == productId) .FirstOrDefaultAsync(); if (photoDto.File != null) { foreach (var file in photoDto.File) { // 2. var uploadResult = new ImageUploadResult(); // 3. if (file.Length > 0) // 4. { 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") }; uploadResult = _cloudinary.Upload(uploadParams); // 5. } } photoDto.Url = uploadResult.Uri.ToString(); // 4. (cont'd) photoDto.PublicId = uploadResult.PublicId; photo = new Photo { Url = photoDto.Url, Description = photoDto.Description, DateAdded = photoDto.DateAdded, PublicId = photoDto.PublicId }; product.Photos.Add(photo); await SaveAll(); } } //return new PhotoForReturn //{ // Id = photo.Id, // Url = photo.Url, // Description = photo.Description, // DateAdded = photo.DateAdded, // IsMain = photo.IsMain, // PublicId = photo.PublicId, //}; return("Them thanh cong"); }
public async Task <PhotoForReturn> AddPhotoForUser(int userId, PhotoForCreation photoDto) { var user = await _context // 1. .Users .Where(u => u.Id == userId) .FirstOrDefaultAsync(); var file = photoDto.File; // 2. var uploadResult = new ImageUploadResult(); // 3. if (file.Length > 0) // 4. { 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") }; uploadResult = _cloudinary.Upload(uploadParams); // 5. } } photoDto.Url = uploadResult.Url.ToString(); // 4. (cont'd) photoDto.PublicId = uploadResult.PublicId; // 4. (cont'd) var photo = new Photo // 6. { Url = photoDto.Url, Description = "", DateAdded = photoDto.DateAdded, PublicId = photoDto.PublicId, User = user }; if (!photo.User.Photos.Any(m => m.IsMain)) // 7. { photo.IsMain = true; } user.Photos.Add(photo); await SaveAll(); // 8. return(new PhotoForReturn // 9. { Id = photo.Id, Url = photo.Url, Description = photo.Description, DateAdded = photo.DateAdded, IsMain = photo.IsMain, PublicId = photo.PublicId }); }
// Photo Upload to cloudinary // FromForm to give a hint to where the rquest is coming from for dubugging purpose public async Task <IActionResult> AddPhotoUser(int Userid, [FromForm] PhotoForCreation photoForCreation) { // compare passed id with the payload id of the user if (Userid != int.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value)) { return(Unauthorized()); } // get user from Repo var userFromRepo = await _repository.GetUser(Userid); // store the uploaded photo var file = photoForCreation.File; // store cloudinary results var uploadResult = new ImageUploadResult(); // check if file is empty if (file.Length > 0) { // use using decorator to dispose of the method from memory after execution using (var stream = file.OpenReadStream()) { // passing our uploadParams to cloudinary var uploadParams = new ImageUploadParams() { File = new FileDescription(file.Name, stream), Transformation = new Transformation().Width(500).Height(500).Crop("fill").Gravity("face") }; uploadResult = _cloudinary.Upload(uploadParams); } } photoForCreation.Url = uploadResult.Url.ToString(); photoForCreation.PublicId = uploadResult.PublicId; // map photoForCreation to Photo var photo = _mapper.Map <Photo>(photoForCreation); // set uploaded picture is the 1st one and set it to main if (!userFromRepo.Photos.Any(u => u.IsMain)) { photo.IsMain = true; } userFromRepo.Photos.Add(photo); if (await _repository.SaveAll()) { var PhotoToReturn = _mapper.Map <PhotoForReturn>(photo); return(CreatedAtRoute("GetPhoto", new { Userid = Userid, id = photo.Id }, PhotoToReturn)); } return(BadRequest("Could not add Photo")); }
public async Task <IActionResult> AddPhotoForUser(int userId, PhotoForCreation photoForCreation) { var user = await _repository.GetUser(userId); if (user == null) { return(BadRequest("Could not find user")); } var currentUserId = int.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value); if (currentUserId != user.Id) { return(Unauthorized()); } var file = photoForCreation.File; var uploadResult = new ImageUploadResult(); 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") }; uploadResult = _cloudinary.Upload(uploadParams); } } photoForCreation.Url = uploadResult.Uri.ToString(); photoForCreation.PublicId = uploadResult.PublicId; var photo = _mapper.Map <Photo>(photoForCreation); photo.User = user; if (!user.Photos.Any(m => m.IsMain)) { photo.IsMain = true; } user.Photos.Add(photo); if (await _repository.SaveAll()) { //photo = await _repository.GetPhotoByPublicId(photo.PublicId); var photoToReturn = _mapper.Map <PhotoForReturnDto>(photo); return(CreatedAtRoute("GetPhoto", new { id = photo.Id }, photoToReturn)); } return(BadRequest("Could not save photo")); }
public async Task <IActionResult> AddPhotoForProduct(int productId, PhotoForCreation photoForCreation) { var product = await this.productRepo.GetProduct(productId, true); if (product == null) { return(BadRequest("Could not find product")); } var file = photoForCreation.File; var uploadResult = new ImageUploadResult(); if (file.Length > 0) { using (var stream = file.OpenReadStream()) { var uploadParams = new ImageUploadParams() { File = new FileDescription(file.Name, stream), Folder = "shop" }; uploadResult = this.cloudinary.Upload(uploadParams); }; photoForCreation.Url = uploadResult.Uri.ToString(); photoForCreation.PublicId = uploadResult.PublicId; var photo = this.mapper.Map <Photo>(photoForCreation); photo.Products = product; if (!product.Photos.Any(x => x.IsMain)) { photo.IsMain = true; } product.Photos.Add(photo); product.LastUpdated = DateTime.Now; if (await this.unitOfWork.CompleteAsync()) { var photoToReturn = this.mapper.Map <PhotoForReturn>(photo); return(CreatedAtRoute("GetPhoto", new { id = photo.Id }, photoToReturn)); } } return(BadRequest("Could not add the photo")); }
public async Task <IActionResult> AddPhotoForUser(int userId, [FromForm] PhotoForCreation photoForCreationDto) { if (userId != int.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value)) { return(Unauthorized()); } var userFromRepo = await _repo.GetUser(userId); var uploadResult = new ImageUploadResult(); var file = photoForCreationDto.File; if (file.Length > 0) { using (var stream = file.OpenReadStream()) { var uploadParams = new ImageUploadParams() { File = new FileDescription(file.FileName, stream), Folder = "DatingApp", Transformation = new Transformation().Width(500) .Height(500).Crop("fill").Gravity("face"), }; uploadResult = _cloudinary.Upload(uploadParams); } } photoForCreationDto.Url = uploadResult.Uri.ToString(); photoForCreationDto.PublicId = uploadResult.PublicId; var photo = _mapper.Map <Photo>(photoForCreationDto); if (!userFromRepo.Photos.Any(p => p.IsMain)) { photo.IsMain = true; } userFromRepo.Photos.Add(photo); if (await _repo.SaveAll()) { var photoToReturn = _mapper.Map <PhotoForReturn>(photo); return(CreatedAtRoute("GetPhoto", new { userId = userId, id = photo.Id }, photoToReturn)); } return(BadRequest("Could not add the photo.")); }
public async Task <IActionResult> AddPhotoForUser(int userId, [FromForm] PhotoForCreation photoForCreation) { if (userId != int.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value)) { return(BadRequest("Could not add photo")); } /*return JsonConvert.SerializeObject(new ErrorCustomized("401", "Unauthorized"));*/ var user = await this.repo.GetUser(userId); var file = photoForCreation.File; var uploadResult = new ImageUploadResult(); 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") }; uploadResult = this.cloudinary.Upload(uploadParams); } } photoForCreation.Url = uploadResult.Uri.ToString(); photoForCreation.PublicId = uploadResult.PublicId; var photo = this.mapper.Map <Photo>(photoForCreation); if (!user.Photos.Any(u => u.IsMain)) { photo.IsMain = true; } user.Photos.Add(photo); if (await this.repo.SaveAll()) { var photoToReturn = this.mapper.Map <PhotoForReturn>(photo); return(CreatedAtRoute("GetPhoto", new { userId = userId, id = photo.Id }, photoToReturn)); /*return JsonConvert.SerializeObject(new CorrectReturn("Photo uploaded correctly"));*/ } return(BadRequest("Could not add photo")); }
public async Task <ActionResult <Photo> > PostPhoto(int userId , [FromForm] PhotoForCreation photoForCreation) { if (userId != int.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value)) { return(Unauthorized()); } var user = await _datingRepository.User(userId); var file = photoForCreation.file; var uploadResult = new ImageUploadResult(); if (file.Length > 0) { using (var stream = file.OpenReadStream()) { var uploadParams = new ImageUploadParams { File = new FileDescription(file.FileName, stream), Transformation = new Transformation().Width(500).Height(500).Crop("fill").Gravity("face") }; uploadResult = _cloudinary.Upload(uploadParams); } photoForCreation.Url = uploadResult.Url.ToString(); photoForCreation.PublicId = uploadResult.PublicId; var photo = _mapper.Map <Photo>(photoForCreation); if (!user.Photos.Any(ph => ph.IsMain)) { photo.IsMain = true; } user.Photos.Add(photo); if (await _datingRepository.SaveAll()) { var photoForReturn = _mapper.Map <PhotoForReturn>(photo); return(CreatedAtRoute(new { userId = userId, id = photo.Id }, photoForReturn)); } } return(BadRequest("Could not add the photo")); }
public async Task <IActionResult> UploadPhoto( Guid ProductId, [FromForm] PhotoForCreation photoForCreationDto) { var prodFromRepo = await _repo.GetProduct(ProductId); var file = photoForCreationDto.file; var uploadResult = new ImageUploadResult(); 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) }; uploadResult = _cloudinary.Upload(uploadParams); } } photoForCreationDto.Url = uploadResult.Uri.ToString(); photoForCreationDto.PublicId = uploadResult.PublicId; var photo = _mapper.Map <Photo> (photoForCreationDto); if (!prodFromRepo.Photos.Any(p => p.IsMain)) { photo.IsMain = true; } else { photo.IsMain = false; } prodFromRepo.Photos.Add(photo); if (await _repo.SaveChanges()) { var photoToReturn = _mapper.Map <PhotoForReturn> (photo); return(CreatedAtRoute(nameof(GetPhoto), new { ProductId, photo.Id }, photoToReturn)); } return(BadRequest("Could not add the photo")); }
public async Task <IActionResult> AddPhotoForUser(int userId, [FromForm] PhotoForCreation photoForCreation) { if (userId != int.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value)) { return(Unauthorized()); } var userFromRepo = await unitOfWork.UserRepository.GetById(userId); var file = photoForCreation.File; var uploadResult = new ImageUploadResult(); 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") }; uploadResult = Cloudinary.Upload(uploadParams); } } photoForCreation.Url = uploadResult.Uri.ToString(); photoForCreation.PublicId = uploadResult.PublicId; var newPhoto = mapper.Map <Photo>(photoForCreation); if (!userFromRepo.Photos.Any(p => p.IsMain)) { newPhoto.IsMain = true; } userFromRepo.Photos.Add(newPhoto); if (await unitOfWork.SaveAll()) { var photoToReturn = mapper.Map <PhotoForReturn>(newPhoto); return(CreatedAtRoute("GetPhoto", new { id = newPhoto.Id }, photoToReturn)); } throw new Exception($"Can't add image to user {userId}"); }
public async Task <IActionResult> AddPhotoForProduct(int productId, PhotoForCreation photoDto) { try { var product = await _productServices.GetProductForUpdate(productId); if (product == null) { return(new BadRequestObjectResult(new { Message = "Không tìm thấy user" })); } var photoForReturn = await _photoService.AddPhotoForProduct(productId, photoDto); if (photoForReturn == null) { return(new BadRequestObjectResult(new { Message = "Tải hình ảnh lên không thành công" })); } return(Ok(photoForReturn)); } catch (Exception ex) { return(new BadRequestObjectResult(new { Message = ex.Message.ToString() })); } }
public async Task <PhotoForReturn> AddPhotoForAnnouncement(Announcement announcement, PhotoForCreation photoForCreation) { var file = photoForCreation.File; var uploadResult = new ImageUploadResult(); 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") }; uploadResult = _cloudinary.Upload(uploadParams); } } photoForCreation.Url = uploadResult.Url.ToString(); photoForCreation.PublicId = uploadResult.PublicId; var photo = _mapper.Map <Photo>(photoForCreation); photo.Id = new Guid(); if (!announcement.Photos.Any(u => u.IsMain)) { photo.IsMain = true; } announcement.Photos.Add(photo); announcement.IsApproved = false; await _context.SaveChangesAsync(); var photoToReturn = _mapper.Map <PhotoForReturn>(photo); return(photoToReturn); }
public async Task <IActionResult> AddPhotoForUser(int userId, [FromForm] PhotoForCreation photoForCreation) { // Verificamos se o usuário que está efetuando a edição é o mesmo que está autenticado na API if (userId != int.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value)) { return(Unauthorized()); } var file = photoForCreation.File; var uploadResult = new ImageUploadResult(); // Se houver um arquivo para upload if (file != null && file.Length > 0) { using (var stream = file.OpenReadStream()) { var uploadParams = new ImageUploadParams() { File = new FileDescription(file.Name, stream), // Vamos aproveitar e fazer uma transformação na foto Transformation = new Transformation() .Width(500).Height(500).Crop("fill").Gravity("face") }; // Executar o upload no Cloudinary uploadResult = _cloudinary.Upload(uploadParams); } } else { BadRequest("Photo is empty."); } var userFromRepo = await _datingRepository.GetUser(userId); // Se houver um erro no Cloudinary vamos propagar ele if (uploadResult.Error != null) { throw new Exception(uploadResult.Error.Message); } var photo = _mapper.Map <Photo>(photoForCreation); photo.IsMain = !userFromRepo.Photos.Any(p => p.IsMain); photo.PublicId = uploadResult.PublicId; photo.Url = uploadResult.Uri.ToString(); photo.DateAdded = DateTime.Now; userFromRepo.Photos.Add(photo); // Salvar a photo no banco if (await _datingRepository.SaveAll()) { // Mapeamos para não passar o usuário da FK também! var photoDetailed = _mapper.Map <PhotoForDetailed>(photo); // AtAction não precisamos dar o nome para a rota (AtRoute) (tá no escopo) // Passamos a foto também return(CreatedAtAction(nameof(GetPhoto), new { id = photo.Id, userId = userId }, photoDetailed)); } else { string errorMsg = "Failed adding photo on server."; _logger.LogError(errorMsg); throw new Exception(errorMsg); } }