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:
Thanks in advance.
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:
Submit the file as multipart/form-data
(i.e. a traditional post). Use [FromForm]
instead (or simply neglect the attribute altogether).
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With