public async Task <IActionResult> Upload(int vehicleId, IFormFile file) { var vehicle = await repository.GetVehicle(vehicleId, eagerLoading : false); if (vehicle == null) { return(NotFound()); } if (file == null) { return(BadRequest("No File")); } if (file.Length == 0) { return(BadRequest("Empty File")); } if (file.Length > photoSettting.MaxBytes) { return(BadRequest("File Too Large")); } if (!photoSettting.IsSupported(file.FileName)) { return(BadRequest("Invalid Type File")); } var uploadsFolderPath = Path.Combine(host.WebRootPath, "uploads"); if (!Directory.Exists(uploadsFolderPath)) { Directory.CreateDirectory(uploadsFolderPath); } var fileName = Guid.NewGuid().ToString() + Path.GetExtension(file.FileName); var filePath = Path.Combine(uploadsFolderPath, fileName); using (var stream = new FileStream(filePath, FileMode.Create)) { await file.CopyToAsync(stream); } var photo = new Photo { FileName = fileName }; vehicle.Photos.Add(photo); await unitOfWork.CompleteAsync(); return(Ok(mapper.Map <Photo, PhotoResource>(photo))); }
public async Task <ActionResult> Upload([FromRoute] int vehicleId, [FromForm] IFormFile file) { if (file == null) { return(BadRequest("Null file")); } if (file.Length == 0) { return(BadRequest("Empty file")); } if (file.Length > PhotoSetting.MaxBytes) { return(BadRequest("File size exceeded")); } if (!PhotoSetting.IsSupported(Path.GetExtension(file.FileName))) { return(BadRequest("File extension not allowed")); } #region Copy photo to Server var uploadsFolderPath = Path.Combine(this.host.WebRootPath, "uploads"); if (!Directory.Exists(uploadsFolderPath)) { Directory.CreateDirectory(uploadsFolderPath); } var fileName = Guid.NewGuid().ToString() + Path.GetExtension(file.FileName); var filePath = Path.Combine(uploadsFolderPath, fileName); using (var stream = new FileStream(filePath, FileMode.Create)) { await file.CopyToAsync(stream); } #endregion #region Save photo path in database var photo = new Photo { FileName = fileName, VehicleId = vehicleId, }; photoDAL.AddVehicle(photo); dbContext.CompleteChanges(); #endregion return(Ok(mapper.Map <Photo, PhotoDTO>(photo))); }