public async Task <IActionResult> AddMediaForProduct(int productId, [FromForm] MediaForCreationDto mediaForCreationDto) { var productFromRepo = await _repo.GetProduct(productId); var file = mediaForCreationDto.File; var newMedia = _mapper.Map <Media>(mediaForCreationDto); if (file.Length > 0) { //check file type with function in Extentions.cs file if (Extentions.CheckFileType(Path.GetExtension(mediaForCreationDto.File.FileName)) != "false") { //generate file name var fileName = productId + "_" + $@"{Guid.NewGuid()}" + Path.GetExtension(mediaForCreationDto.File.FileName).ToString(); var filePath = Path.Combine(Directory.GetCurrentDirectory(), @"wwwroot\images", fileName); //save file in folder using (var fileStream = new FileStream(filePath, FileMode.Create)) { await mediaForCreationDto.File.CopyToAsync(fileStream); } //check file type var type = Extentions.CheckFileType(Path.GetExtension(mediaForCreationDto.File.FileName)); newMedia.Url = fileName; newMedia.Type = type; newMedia.Description = mediaForCreationDto.File.FileName; newMedia.Status = "Temp"; //add file to table productFromRepo.Media.Add(newMedia); } else { return(BadRequest("not a valid file")); } } if (await _repo.SaveAll()) { var mediaToReturn = _mapper.Map <MediaForReturnDto>(newMedia); return(CreatedAtRoute("GetMedia" , new { productId = productId, id = newMedia.Id } , mediaToReturn)); } return(BadRequest("could not add the photo")); }