public async Task <IActionResult> SetLogo(string orgName, [FromForm] PhotoForCreationDTO photoForCreation) { if (HttpContext.Items.ContainsKey("organization")) { var org = HttpContext.Items["organization"] as Organization; if (org.Logo == null) { org.Logo = new Photo { Organization = org }; this.photoRepo.AddPhotoFile(org.Logo, photoForCreation.File); } else { this.photoRepo.UpdatePhotoFile(org.Logo, photoForCreation.File); } if (await this.photoRepo.SaveChangesAsync()) { var photoToReturn = this.mapper.Map <PhotoToReturnDTO>(org.Logo); return(Ok(photoToReturn)); } return(BadRequest("Could not set the organization logo")); } return(NotFound($"{orgName} organizaiton isn't exist")); }
public async Task <Result <PhotoForDetailedDTO> > AddAsync(PhotoForCreationDTO model, int adId) { var file = model.File; if (file == null) { return("Снимката не е намерена"); } var uploadResult = UploadToCloudinary(file); model.Url = uploadResult.Uri.ToString(); model.PublicId = uploadResult.PublicId; var photo = this.mapper.Map <Photo>(model); var ad = await this.data.Ads .Include(a => a.Photos) .IgnoreQueryFilters() .Where(a => a.Id == adId && a.IsDeleted == false) .FirstOrDefaultAsync(); var adAlreadyHasMainPhoto = ad.Photos.Any(p => p.IsMain && !p.IsDeleted); if (!adAlreadyHasMainPhoto) { photo.IsMain = true; } ad.Photos.Add(photo); await this.data.SaveChangesAsync(); return(this.mapper.Map <Photo, PhotoForDetailedDTO>(photo)); }
public async Task <IActionResult> AddPhotoForUser(int userId, PhotoForCreationDTO photoDTO) { var user = await _repo.GetUser(userId); if (user == null) { return(BadRequest("Nie znaleziono takiego uzytkownika")); } var curentUserId = int.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value); if (user.Id != curentUserId) { return(Unauthorized()); } //Przesłany plik var file = photoDTO.File; // Present file in HTTP REQUEST // ImagUpLoadResult to tez klasa Cloudinary 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(1000).Height(1000).Crop("fill").Gravity("face") }; // wysyłamy zdjęcie do Cloudinary uploadResult = _cloudinary.Upload(uploadParams); } } photoDTO.Url = uploadResult.Uri.ToString(); photoDTO.PublicId = uploadResult.PublicId; var photo = _mapper.Map <Photos>(photoDTO); photo.User = user; if (!user.Photos.Any(m => m.IsMain)) { photo.IsMain = true; } user.Photos.Add(photo); // var photoToReturn = _mapper.Map<PhotoForReturnDTO>(photo); PRZENIESIONE DO Ifa poniżej aby pobierane było z ID if (await _repo.SaveAll()) { var photoToReturn = _mapper.Map <PhotoForReturnDTO>(photo); // tutaj juz każde photo ma ID return(CreatedAtRoute("GetPhoto", new { id = photo.Id }, photoToReturn)); // TUTAJ WSTAWIONY będzie przekierowanie do GetPhoto } return(BadRequest("Nie można dodać foto")); }
public async Task <IActionResult> AddPhotoForUser(int id, [FromForm] PhotoForCreationDTO photoForCreationDTO) { if (id != int.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value)) { return(Unauthorized()); } var userFromRepo = await this._repo.GetUser(id); var savedPhoto = this._pr.AddPhoto(photoForCreationDTO); var photo = _mapper.Map <UserPhoto>(savedPhoto); if (!userFromRepo.Photos.Any(u => u.IsMain)) { photo.IsMain = true; } userFromRepo.Photos.Add(photo); if (await this._repo.SaveAll()) { var photoToReturn = _mapper.Map <PhotoForReturnDTO>(photo); return(CreatedAtRoute("GetPhoto", new { userId = userFromRepo.Id, Id = photo.Id }, photoToReturn)); } return(BadRequest()); }
public PhotoForCreationDTO AddPhoto(PhotoForCreationDTO photo) { var file = photo.File; var result = 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") }; result = cloudinary.Upload(uploadParams); } photo.Url = result.Url.ToString(); photo.PublicId = result.PublicId; } return(photo); }
public async Task <IActionResult> SetUserPhoto([FromForm] PhotoForCreationDTO photoForCreation) { if (ModelState.IsValid) { var user = await this.userRepo.FindByNameAsync(User.FindFirst(ClaimTypes.Name).Value); if (user != null && user.Id == User.FindFirst(ClaimTypes.NameIdentifier).Value) { if (user.Photo == null) { user.Photo = new Photo { User = user }; this.photoRepo.AddPhotoFile(user.Photo, photoForCreation.File); } else { this.photoRepo.UpdatePhotoFile(user.Photo, photoForCreation.File); } if (await this.photoRepo.SaveChangesAsync()) { var photoToReturn = this.mapper.Map <PhotoToReturnDTO>(user.Photo); return(Ok(photoToReturn)); } return(BadRequest("Could not set the user photo")); } return(Unauthorized()); } return(BadRequest(ModelState)); }
public async Task <IActionResult> AddPhotoForUser(int userId, [FromForm] PhotoForCreationDTO photoForCreation) { // Compare user id against root parameter, authorize the user var isCurrentUser = int.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value) == userId; if (!isCurrentUser) { return(Unauthorized()); } //Get the user from repository var user = await _repository.GetUser(userId, isCurrentUser); // Get the file that we're sending to this api call var file = photoForCreation.File; // Cloudinary class where we store upload result var uploadResult = new ImageUploadResult(); if (file.Length > 0) { // Create new file stream by reading the contents of the file we're uploading using (var stream = file.OpenReadStream()) { // Create our upload parameters var uploadParams = new ImageUploadParams() { File = new FileDescription(file.Name, stream), // Cloudinary transformation, we're cropping photos and focusing on user's face Transformation = new Transformation().Width(500).Height(500).Crop("fill").Gravity("face") }; // Cloudinary upload method, this is where we upload the photo to Cloudinary uploadResult = _cloudinary.Upload(uploadParams); // This also returns important info such as image URL and public key we need to store in our db for later accessing } } // Get Url and PublicId from Cloudinary upload result photoForCreation.Url = uploadResult.Uri.ToString(); photoForCreation.PublicId = uploadResult.PublicId; var photo = _mapper.Map <Photo>(photoForCreation); // If the users hasn't got any photos, set this one to be main photo if (!user.Photos.Any(u => u.IsMain)) { photo.IsMain = true; } // Store our photo object in our db user.Photos.Add(photo); if (await _repository.SaveAll()) { // photoToReturn is information we're sending back to the client var photoToReturn = _mapper.Map <PhotoForReturnDTO>(photo); // CreatedAtRoute call our GetPhoto method to return photo information back to the client return(CreatedAtRoute("GetPhoto", new { id = photo.Id }, photoToReturn)); } return(BadRequest("Could not add the photo")); }
public async Task <IActionResult> AddPhotoToUser(int userId, PhotoForCreationDTO photoForCreationDTO) { var user = await dataContext.GetUserAsync(userId); if (user == null) { return(BadRequest("Couldn't find user")); } var currentUserId = int.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value); if (userId != currentUserId) { return(Unauthorized()); } 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(1000).Height(1000).Crop("fill").Gravity("face") }; uploadResult = photoCloud.Upload(uploadParams); } } photoForCreationDTO.URL = uploadResult.Uri.ToString(); photoForCreationDTO.PublicId = uploadResult.PublicId.ToString(); var photo = mapper.Map <Photo>(photoForCreationDTO); photo.User = user; if (!user.Photos.Any(m => m.MainPhoto)) { photo.MainPhoto = true; } dataContext.AddAsync <Photo>(photo); if (await dataContext.SaveAllAsync()) { var photoToReturn = mapper.Map <PhotoForReturnDTO>(photo); return(CreatedAtRoute("GetPhoto", new { id = photo.Id }, photoToReturn)); } return(BadRequest("Couldn't add thephoto")); }
public async Task <IActionResult> AddPhotoForUser(int userId, PhotoForCreationDTO photoDto) { var user = await _repo.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 = photoDto.File; var uploadResult = new ImageUploadResult(); if (file.Length > 0) { using (var stream = file.OpenReadStream()) { var uploadParams = new ImageUploadParams() { File = new FileDescription(file.Name, stream) }; uploadResult = _cloudinary.Upload(uploadParams); } } photoDto.Url = uploadResult.Uri.ToString(); photoDto.PublicId = uploadResult.PublicId; var photo = _mapper.Map <Photo>(photoDto); photo.User = user; if (!user.Photos.Any(m => m.IsMain)) { photo.IsMain = true; } user.Photos.Add(photo); if (await _repo.SaveAll()) { var photoToReturn = _mapper.Map <PhotoForReturnDTO>(photo); return(CreatedAtRoute("GetPhoto", new { id = photo.Id }, photoToReturn)); } return(BadRequest("Could not add the photo")); }
public async Task <IActionResult> AddPhotos(int userId, [FromForm] PhotoForCreationDTO photoForCreation) { if (userId != Convert.ToInt32(User.FindFirst(ClaimTypes.NameIdentifier).Value)) { return(Unauthorized()); } var user = await _repo.GetUser(userId); var file = photoForCreation.File; if (file is null) { return(BadRequest("No file found to upload.")); } 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(400).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(a => a.IsMain)) { photo.IsMain = true; } user.Photos.Add(photo); if (await _repo.SaveAll()) { var photoToReturn = _mapper.Map <PhotoForReturnDTO>(photo); //Not working in my case //return CreatedAtRoute("GetPhoto", new { id = photo.Id }, photoToReturn); return(Ok(photoToReturn)); } return(BadRequest("Couldn't add the photo")); }
public async Task <IActionResult> AddPhoto(PhotoForCreationDTO photoDTO, int userId) { var user = await _repo.GetUser(userId); if (user == null) { return(BadRequest("Could not find user")); } var currentUserId = int.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value); if (currentUserId != userId) { return(Unauthorized()); } var file = photoDTO.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(1000).Height(1000).Crop("fill").Gravity("face") }; uploadResult = _cloudinary.Upload(uploadParams); } } photoDTO.Url = uploadResult.Uri.ToString(); photoDTO.publicId = uploadResult.PublicId; var photo = _mapper.Map <Photo>(photoDTO); photo.User = user; if (!user.Photos.Any(p => p.isMainPhoto = true)) { photo.isMainPhoto = true; } user.Photos.Add(photo); if (await _repo.SaveAll()) { var photoToReturn = _mapper.Map <PhotoForReturnDTO>(photo); return(CreatedAtRoute("GetPhoto", new { id = photo.Id }, photoToReturn)); } return(BadRequest("Could not add photo")); }
public async Task <IActionResult> AddPhotoForUser(int userId, [FromForm] PhotoForCreationDTO photoForCreatinonDTO) { if (userId != int.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value)) { return(Unauthorized()); } var userFromRepo = await _repo.GetUser(userId); var file = photoForCreatinonDTO.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); } } photoForCreatinonDTO.Url = uploadResult.Uri.ToString(); photoForCreatinonDTO.PublicId = uploadResult.PublicId; var photo = _mapper.Map <Photo>(photoForCreatinonDTO); if (!userFromRepo.Photos.Any(u => u.IsMain)) { photo.IsMain = true; } userFromRepo.Photos.Add(photo); if (await _repo.SaveAll()) { var photoForReturn = _mapper.Map <PhotoForReturnDTO>(photo); return(CreatedAtRoute( "GetPhoto", new { userId = userId, id = photo.Id }, photoForReturn)); } return(BadRequest("Could not add the photo")); }
public ActionResult AddPhotoForCity(int cityId, [FromForm] PhotoForCreationDTO photoForCreationDto) { var city = _appRepository.GetCityById(cityId); if (city == null) { return(BadRequest("Could not find the city")); } var currentUserId = int.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value); if (currentUserId != city.UserId) { return(Unauthorized()); } 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) }; uploadResult = _cloudinary.Upload(uploadParams); } } photoForCreationDto.Url = uploadResult.Uri.ToString(); photoForCreationDto.PublicId = uploadResult.PublicId; var photo = _mapper.Map <Photo>(photoForCreationDto); photo.City = city; if (!city.Photos.Any(p => p.IsMain)) { photo.IsMain = true; } city.Photos.Add(photo); if (_appRepository.saveAll()) { var photoToReturn = _mapper.Map <PhotoForReturnDTO>(photo); return(CreatedAtRoute("GetPhoto", new { id = photo.Id }, photoToReturn)); } return(BadRequest("Could not add the photo")); }
public async Task <ActionResult> Add([FromForm] PhotoForCreationDTO model, [FromQuery] int adId) { var result = await this.photos.AddAsync(model, adId); if (result.Failure) { return(BadRequest(result.Error)); } return(Created(nameof(this.Add), result.Data)); }
public async Task <IActionResult> AddPhoto(int id, [FromForm] PhotoForCreationDTO photoForCreationDTO) { var space = await _repository.GetSpace(id); if (space == null) { return(BadRequest("Cannot upload photo for unexisting entity")); } var file = photoForCreationDTO.File; if (file.Length > _photoSettings.MaxBytes) { return(BadRequest("Maximum file size exceeded")); } if (!_photoSettings.isSupported(file.FileName)) { return(BadRequest("Invalid file type.")); } 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); } } photoForCreationDTO.FileName = uploadResult.Uri.ToString(); photoForCreationDTO.PublicId = uploadResult.PublicId; photoForCreationDTO.SpaceId = id; var photo = _mapper.Map <Photo>(photoForCreationDTO); space.Photos.Add(photo); // _repository.Add(photo); if (await _repository.SaveAllChanges()) { var photoToReturn = _mapper.Map <PhotoToReturnDTO>(photo); return(Ok(photoToReturn)); } return(BadRequest("Could not add photo")); }
public async Task <IActionResult> AddPhotoForUser(int userId, [FromForm] PhotoForCreationDTO photoForCreationDTO) //FromForm porque estamos recebendo um form e não um json no body { if (userId != int.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value)) { return(Unauthorized()); } var userFromRepo = await _repository.GetUser(userId); 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.FileName, stream), Transformation = new Transformation().Width(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(u => u.IsMain)) { photo.IsMain = true; } userFromRepo.Photos.Add(photo); if (await _repository.SaveAll()) { //o photoToReturn está aqui apenas porque o photo.Id só é gerado após persistir no banco var photoToReturn = _mapper.Map <PhotoForReturnDTO>(photo); return(CreatedAtRoute("GetPhoto", new { userId, id = photo.Id }, photoToReturn)); //return Ok(photoToReturn); } return(BadRequest("Could not upload the photo")); }
public async Task <IActionResult> AddPhotoForUser(Guid userId, [FromForm] PhotoForCreationDTO photocreated) { var claim = User.FindFirst(ClaimTypes.NameIdentifier).Value; if (userId.ToString() != claim) { return(Unauthorized("Access Denied")); } var userFromRepo = await _repository.GetUser(userId); var file = photocreated.File; var uploadImage = new ImageUploadResult(); if (file.Length > 0) { using (var stream = file.OpenReadStream()) { var uploadValues = new ImageUploadParams() { File = new FileDescription(file.Name, stream), Transformation = new Transformation().Width(500).Height(500).Crop("fill").Gravity("face") }; uploadResult = cloudinary.Upload(uploadValues); } } photocreated.Url = uploadResult.Uri.ToString(); photocreated.PublicId = uploadResult.PublicId; var photoSave = _mapper.Map <Photo>(photocreated); photoSave.PhotoUniqueIdentifier = Guid.NewGuid(); photoSave.UserUniqueID = userId; if (!userFromRepo.Photos.Any(x => x.IsMain)) { photoSave.IsMain = true; } userFromRepo.Photos.Add(photoSave); if (await _repository.SaveAll()) { var photoToReturn = _mapper.Map <PhotoReturnDTO>(photoSave); return(CreatedAtRoute("GetPhoto", new{ unique = photoSave.PhotoUniqueIdentifier }, photoToReturn)); } return(BadRequest("Could not add the photo")); }
public async Task <IActionResult> AddPhoto(int id, [FromForm] PhotoForCreationDTO photoForCreationDTO) { var singleEvent = await _repository.GetEvent(id); if (singleEvent == null) { return(BadRequest("Cannot upload photo for unexisting entity")); } var file = photoForCreationDTO.File; if (file.Length > _photoSettings.MaxBytes) { return(BadRequest("Maximum file size exceeded")); } if (!_photoSettings.isSupported(file.FileName)) { return(BadRequest("Invalid file type.")); } var uploadResult = new ImageUploadResult(); if (file.Length > 0) { using (var stream = file.OpenReadStream()) { var uploadParams = new ImageUploadParams() { File = new FileDescription(file.Name, stream) }; uploadResult = _cloudinary.Upload(uploadParams); } } photoForCreationDTO.FileName = uploadResult.Uri.ToString(); photoForCreationDTO.PublicId = uploadResult.PublicId; photoForCreationDTO.EventId = id; var photo = _mapper.Map <Photo>(photoForCreationDTO); singleEvent.Images.Add(photo); if (await _repository.SaveAllChanges()) { return(Ok()); } return(BadRequest("Could not add photo")); }
public async Task <IActionResult> AddPhotoForUser(int userId, [FromForm] PhotoForCreationDTO photoDto) { //if now user id != modify user id ==> no right to change if (userId != int.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value)) { return(Unauthorized()); } var userFromRep = await _repository.GetUser(userId); var file = photoDto.File; var uploadResult = new ImageUploadResult(); if (file.Length > 0) { using (var stream = file.OpenReadStream()){ var imageUploadparam = new ImageUploadParams() { File = new FileDescription(file.Name, stream), //if photo is too large, focuse on face and square shape and crop. Transformation = new Transformation().Width("500").Height("500").Crop("fill").Gravity("face") }; uploadResult = this._cloudinary.Upload(imageUploadparam); } } photoDto.Url = uploadResult.Uri.ToString(); photoDto.PublicId = uploadResult.PublicId; var addphoto = _mapper.Map <Photo>(photoDto); if (!userFromRep.Photos.Any(x => x.IsMain == true)) { addphoto.IsMain = true; } userFromRep.Photos.Add(addphoto); if (await _repository.SaveAll()) { var photoForReturn = _mapper.Map <PhotoForReturnDto>(addphoto); return(CreatedAtRoute("GetPhoto", new { userId = userId, id = addphoto.Id }, photoForReturn)); } return(BadRequest("Could Not add Photo")); }
public async Task <IActionResult> UploadPhoto(int userid, [FromForm] PhotoForCreationDTO photo) { if (userid != int.Parse(User.FindFirst(System.Security.Claims.ClaimTypes.NameIdentifier).Value)) { return(Unauthorized()); } //chon id mostaqiman tu url migirm bayad check konm ba id dakhele jwt token var user = await rep.GetUser(userid); var file = photo.File;//fili k tu httprequestm bude var uploadResult = new ImageUploadResult(); if (file.Length > 0) // check to see if the file is empty { using (var stream = file.OpenReadStream() // shoru mikone b khundm file ) { var uploadParams = new ImageUploadParams(); uploadParams.File = new FileDescription(file.Name, stream); Transformation t = new Transformation(); uploadParams.Transformation = t.Width(500).Height(500).Crop("fill").Gravity("face"); uploadResult = c.Upload(uploadParams); } } photo.Url = uploadResult.Uri.ToString(); photo.PublicId = uploadResult.PublicId; var newPhoto = mapper.Map <Photo>(photo); if (!user.Photos.Any(e => e.IsMain)) { newPhoto.IsMain = true; } // newPhoto.UserId = u; // newPhoto.User= user; user.Photos.Add(newPhoto); if (await rep.SaveAll()) { var phototoreturn = mapper.Map <PhotoForReturnDTO>(newPhoto); return(CreatedAtRoute("GetPhoto", new { id = newPhoto.Id }, phototoreturn)); } return(BadRequest("can't save the photo")); }
public async Task <IActionResult> AddPhotoForUser(int userId, [FromForm] PhotoForCreationDTO Image) { if (userId != int.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value)) { return(Unauthorized()); } var userFromRepo = this.IdatingService.GetUserById(userId); var file = Image.FormFile; 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); } } Image.URl = uploadResult.Uri.ToString(); Image.PublicId = uploadResult.PublicId; Image.UserId = userId; var result = Mapper.Map <Photo>(Image); this.IdatingService.SavePicture(result, out int Id); if (Id > 0) { return(CreatedAtRoute("GetPhoto", new{ id = Id }, result)); //return redirect to action } //take it to repository and save it there return(BadRequest("Error Try Again")); }
public async Task <IActionResult> AddPhotoForUser(long userId, [FromForm] PhotoForCreationDTO photoForCreationDTO) { if (userId != long.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value)) { return(StatusCode(StatusCodes.Status401Unauthorized)); } var user = await _datingRepository.GetUser(userId); 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).Crop("fill").Gravity("face") }; uploadResult = await _cloudinary.UploadAsync(uploadParams); } photoForCreationDTO.Url = uploadResult.Uri.ToString(); photoForCreationDTO.PublicId = uploadResult.PublicId; var photo = _mapper.Map <Photo>(photoForCreationDTO); photo.IsProfilePic = !user.Photos.Any(x => x.IsProfilePic); user.Photos.Add(photo); if (await _datingRepository.SaveAll()) { var photoToReturn = _mapper.Map <PhotoForReturnDTO>(photo); return(CreatedAtRoute(nameof(GetPhoto), new { userId, id = photo.Id }, photoToReturn)); } return(StatusCode(StatusCodes.Status400BadRequest, "Could not add the photo")); }
// we give FromForm so that .Net Core a hint that the information is coming the form // otherwise we get input not valid error. public async Task <IActionResult> AddPhotoForUser(int userID, [FromForm] PhotoForCreationDTO photoForCreationDTO) { if (userID != int.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value)) { return(Unauthorized()); } var userFromRepo = await _datingRepo.GetUser(userID, true); var file = photoForCreationDTO.File; // result we get back from cloudinary var uploadResult = new ImageUploadResult(); if (file.Length > 0) { using (var stream = file.OpenReadStream()) // Opens the request stream for reading the uploaded file. { var uploadParams = new ImageUploadParams() { File = new FileDescription(file.Name, stream), // this is to transform photo square shape to round for eg Transformation = new Transformation().Width(500).Height(500).Crop("fill").Gravity("face") }; uploadResult = _cloudinary.Upload(uploadParams); } } // Each media asset uploaded to Cloudinary is assigned an unique Public ID and is available for immediate delivery and transformation. // The upload method returns an instance of ImageUploadResult class that contains a set of properties // of the uploaded image, including the image URL and Public ID, which is what we are using below photoForCreationDTO.Url = uploadResult.Uri.ToString(); photoForCreationDTO.PublicID = uploadResult.PublicId; // map the photo to dto var photo = _mapper.Map <Photo>(photoForCreationDTO); // alternate to the above is Photo photo = new Photo(); // _mapper.Map(photoForCreationDTO, photo); // if this is the first photo and hence no main photo set for the user if (!userFromRepo.Photos.Any(u => u.IsMain)) { photo.IsMain = true; } userFromRepo.Photos.Add(photo); if (await _datingRepo.SaveAll()) { var photoToReturn = _mapper.Map <PhotoForReturnDTO>(photo); // returning location header with the location of the created results // CreatedAtRoute adds a Location header to the response. The Location header specifies the URI of the newly created to-do item. // for eg: http://localhost:5000/api/users/1/photos/11 after the photo with id 11 is uploaded return(CreatedAtRoute("GetPhoto", new { id = photo.ID }, photoToReturn)); } return(BadRequest("Could not add the photo")); }