public async Task UploadAdImages(Guid adId, AdUploadPhotosModel images) { foreach (var photo in images.Images) { var fileName = photo.FileName; var extension = Path.GetExtension(fileName); var newFileName = $"{Guid.NewGuid()}{extension}"; var filePath = Path.Combine(_webHostEnvironment.ContentRootPath, "wwwroot", "AdImages", newFileName); await using var fileStream = new FileStream(filePath, FileMode.Create, FileAccess.Write); await photo.CopyToAsync(fileStream); var photoUrl = $"{_httpContextAccessor.HttpContext.Request.Scheme}://{_httpContextAccessor.HttpContext.Request.Host.Value}/wwwroot/AdImages//{newFileName}"; var adPhoto = new AdPhotoDetailsModel { Id = Guid.NewGuid(), AdId = adId, ImageUrl = photoUrl }; var mapped = _mapper.Map <AdImage>(adPhoto); await _dataContext.AdImages.AddAsync(mapped); } await _dataContext.SaveChangesAsync(); }
public async Task <IActionResult> UploadPhotos(Guid adId, [FromForm] AdUploadPhotosModel images) { var ad = await _adService.GetAdByIdAsync(adId); if (ad == null) { return(NotFound("Such ad does not exists.")); } var userOwnsPost = await _adService.UserOwnsPostAsync(adId, HttpContext.GetUserId()); if (!userOwnsPost.Success) { return(BadRequest(new { error = "You do not own this ad" })); } await _adService.UploadAdImages(adId, images); return(Ok()); }