0
votes

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

2
Please debug your project. Is fileStream really null? Can you look at the Request object to see what data is being received? You should be able to see what fields the posted form actually contains. Also check with Postman’s dev tools to see what the actual request is that is being sent there.poke
thanks for the suggestion. It was null somehow.Exception handler

2 Answers

0
votes

The FromBody attribute can only be used on one parameter in the signature. One option to send the int vId is by a query string and read it with the FromQuery attribute.

Try it like this

[HttpPost]
public async Task<IActionResult> Upload([FromQuery]int vId, [FromBody]IFormFile fileStream) 

Then make the POST to url api/yourController?vId=123456789 where the body contains the IFromFile

Update

As the form-data will be sent as key-value try and create a model containing the keys and read it from the body

public class RequestModel
{
    public IFormFile fileStream { get; set; }
}

Then read the model from the body

[HttpPost]
public async Task<IActionResult> Upload([FromBody]RequestModel model) 
-1
votes

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