Search code examples
c#asp.net-corepostmanasp.net-core-webapiiformfile

Could not upload photo using IFormFile object in ASP.Net Core 2 with null reference expception


I tried to upload a photo using IFormFile using a postman plugin. But the API didn't get the file object from the body of the request. I tried with and without [FromBody].

[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);
    }

The error shows on this line :

    var fileName = Guid.NewGuid().ToString() + Path.GetExtension(fileStream.FileName);

I figured out that it is not getting the file, while I am sending an image.jpg with the same key "fileStream". By the way everything else works fine. I found no solution to fix this issue. If anybody can help me with this please let me know.

enter image description here


Solution

  • Finally got the solution. Actually the problem was with the old version of postman Tabbed Postman - REST Client chrome extension. After trying with new postman app it worked perfectly fine. Thanks all of you who tried to solve this problem. Here is the result:enter image description here