vega
vega copied to clipboard
Can not upload image with null Reference exception
My code is completely similar to yours. I have only one issue testing the photo upload api. It seems like my api is not getting a IFormFile object from the body of the request. Here's the proof: This is the action: ` [HttpPost] public async Task<IActionResult> Upload(int vId,IFormFile fileStream) { var vehicle = await this.repository.GetVehicle(vId, hasAdditional: false); if (vehicle == null) return NotFound(); var uploadsFolderPath = Path.Combine(host.WebRootPath, "uploads"); if (!Directory.Exists(uploadsFolderPath)) Directory.CreateDirectory(uploadsFolderPath); var fileName = Guid.NewGuid().ToString() + Path.GetExtension(fileStream.FileName); var filePath = Path.Combine(uploadsFolderPath, fileName);
using (var stream = new FileStream(filePath, FileMode.Create))
{
await fileStream.CopyToAsync(stream);
}
var photo = new Photo { FileName = fileName };
vehicle.Photos.Add(photo);
await unitOfWork.CompleteAsync();
return Ok(mapper.Map<Photo,PhotoResource>(photo));
}
and the controller with constructor:
public class PhotosController : Controller
{
private readonly IHostingEnvironment host;
private readonly IVehicleRepository repository;
private readonly IMapper mapper;
private readonly IUnitOfWork unitOfWork;
public PhotosController(IHostingEnvironment host, IVehicleRepository repository,IUnitOfWork unitOfWork, IMapper mapper)
{
this.mapper = mapper;
this.repository = repository;
this.host = host;
}`
error shows on this line:
var fileName = Guid.NewGuid().ToString() + Path.GetExtension(fileStream.FileName);
which indicates its not getting the "file" object while I am sending an image.jpg with the same key "fileStream".