Search code examples
asp.net-corepostman

Error 415 while uploading a file through Postman to ASP.NET Core API


I'm trying to upload a file through ASP.NET Core API. My action is:

[HttpPost]
[Route("{id}")]
public async Task<IActionResult> PostImage([FromBody] IFormFile file, [FromRoute] int id)
{
    if(file.Length > 0)
    {
        var fileName = Path.GetFileName(file.FileName);
        var fileExtension = Path.GetExtension(fileName);
        var path = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot/images", "Image-" + id + "." + fileExtension);
        using (var stream = new FileStream(path, FileMode.Create))
        {
            await file.CopyToAsync(stream);
        }
        return Ok(fileName + fileExtension);
    }
    return NotFound("File not found!");
}

When I use Postman to check its functionality, I encounter Error 415 and Visual Studio does not jump to the breaking point:

{ "type": "https://tools.ietf.org/html/rfc7231#section-6.5.13", "title": "Unsupported Media Type", "status": 415, "traceId": "00-d411f8c099a9ca4db6fe04ae25c47411-dadd8cca7cc36e45-00" }

How can I fix this problem in my code?


Solution

  • If you want to receive IFormFile, you need post content-type=multipart/form-data which is from form data instead of body. Also remember to change [FromBody] to [FromForm].

    Postman: enter image description here

    Controller:

    [HttpPost]
    [Route("{id}")]
    public async Task<IActionResult> PostImage([FromForm] IFormFile file, [FromRoute] int id)    
    {...}
    

    If you post file from body, maybe you post a byte array. If though you need change IFormFile file to byte[] file.