Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 935
Андрей Ляшенко Avatar asked Sep 17 '25 23:09

Андрей Ляшенко


2 Answers

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.

like image 147
Tseng Avatar answered Sep 19 '25 13:09

Tseng


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.

like image 42
Hasan Avatar answered Sep 19 '25 15:09

Hasan