Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

File POST returns error 415

I'm trying to make a file upload feature in my ASP.NET Core 2 project.
I receive this response when sending the POST call to my WEBApi service:

Status Code: 415; Unsupported Media Type

My Controller action looks like this:

    [HttpPost]
    [Route("Upload")]
    [Authorize]
    public Guid Post([FromBody]IFormFile file)
    {
        Stream readStream = file.OpenReadStream();

        byte[] fileData = new byte[file.Length];

        readStream.Read(fileData, 0, fileData.Length);

        return _printServiceManager.SaveFile(fileData);
    }

I'm calling it either from my Angular 6 client app and from Postman but nothing changes. I found an existing question here about this topic, but the solution given is to change my header to "Content-Type: application/json". No changes.
Then I tried searching some other hint online but the only one I found tells me to change again the content type header as this: "Accept: application/json". Not working too.

Maybe I'm asking something simple or that I should know as a web developer, but I come from a back-end oriented career and I'm trying to figure out what's wrong with my code. So if you have some complete resource about the topic, please share it!

Tried to change again the content type as suggested, but I obtain the same result:
enter image description here

Thanks in advance.

like image 699
mororo Avatar asked Feb 04 '23 22:02

mororo


1 Answers

By definition IFormFile cannot be obtained using FromBody. IFormFile only works with multipart/form-data encoded requests, whereas FromBody only works with JSON or XML request bodies.

As a result, you have two paths:

  1. Submit the file as multipart/form-data (i.e. a traditional post). Use [FromForm] instead (or simply neglect the attribute altogether).

  2. Actually submit the file as JSON, in which case you'll need to bind to a class to represent the JSON object you're posting. The file data should be a base64-encoded string in your JSON object and you'll then bind that to a property of type byte[]. ASP.NET Core will take care of decoding the base64 string into a byte array.

like image 128
Chris Pratt Avatar answered Feb 06 '23 11:02

Chris Pratt