Why file IFormFile = null?

[Route("api/file")]
[Produces("application/json")]
[Consumes("application/json", "application/json-patch+json", "multipart/form-data")]
[ApiController]
public class FileController : ControllerBase
{
    public FileController()
    {
    }

    [HttpPost]
    public async Task<IActionResult> PostProfilePicture([FromQuery]IFormFile file)
    {
        var stream = file.OpenReadStream();
        var name = file.FileName;
        return null;
    }
}

Postman

enter image description here

Debug

enter image description here

In the end file = null How to solve this problem?

Upvotes: 3

Views: 6605

Answers (3)

Hasan
Hasan

Reputation: 1298

I guess you're getting null from IFormFile because you specify required attributes for this operation on the Controller class, not on the controller method. Updating your code as below will solve the problem.

[Route("api/file")]
[ApiController]
public class FileController : ControllerBase
{

    public FileController()
    {

    }

    [HttpPost]
    [Produces("application/json")]
    [Consumes("multipart/form-data")]
    public async Task<IActionResult> PostProfilePicture([FromForm]IFormFile file)
    {
        var stream = file.OpenReadStream();
        var name = file.FileName;
        return null;
    }
}

Hope this solves your problem.

Upvotes: 2

Tseng
Tseng

Reputation: 64170

You are sending it as x-www-form-urlencoded. You have to send it as multipart/form-data. File uploads only possible in this mode, hence also IFormFile will be null on all other modes.

x-www-form-urlencoded is the default mode and only use for sending key/vale encoded pairs within the request body.

Also [FromQuery] isn't necessary, because you can't upload files via query parameters.

Upvotes: 2

Darjan Bogdan
Darjan Bogdan

Reputation: 3900

You need to change attribute which selects source from which model binder will resolve IFormFile instance. Instead of [FromQuery] to [FromForm]:

public async Task<IActionResult> PostProfilePicture([FromForm]IFormFile file)

Upvotes: 1

Related Questions