I am trying to upload a file to a server so i am trying to use @RequestBody to get the data of the file, but i am getting 415 error code while trying to upload a file.
So i have googled(got solution to upload a file) and got to know that i cant get file data from a request body. So i want to know why cant we access file data from request body as data will be sent in request body in HTTP requests, so i want to know how is the request happening in the case of uploading a file.
My server code before:
@RequestMapping(value = "/upload",headers = "Content-Type=multipart/form-data", method = RequestMethod.POST)
@ResponseBody
public String upload(@RequestBody MultipartFile file)
{
}
Solution:
@RequestMapping(value = "/upload",headers = "Content-Type=multipart/form-data", method = RequestMethod.POST)
@ResponseBody
public String upload(MultipartHttpServletRequest request)
{
}
The handler for @RequestBody reads the body and binds it to the parameter. The handler for @RequestParam can then get the request parameter from the URL query string. The handler for @RequestParam reads from both the body and the URL query String.
Simply put, the @RequestBody annotation maps the HttpRequest body to a transfer or domain object, enabling automatic deserialization of the inbound HttpRequest body onto a Java object. Spring automatically deserializes the JSON into a Java type, assuming an appropriate one is specified.
Thanks. spring v5. 3.6 supports request body with GET.
@RequestBody: Annotation is used to get request body in the incoming request. Note: First we need to establish the spring application in our project. Step 2: Click on Generate which will download the starter project. Step 3: Extract the zip file.
Technically you could write your own HttpMessageConverter
which would parse the full multipart request body, but you'd have to have a very specific target type that could handle all the parts.
You'll notice from the javadoc of @RequestBody
Annotation indicating a method parameter should be bound to the body of the web request.
that the intention is to bind the entirety of the request body to the method parameter. How do you bind every part of a multipart request to a single parameter? Something like a MultiValueMap<String, Object>
(which is what FormHttpMessageConverter
uses when writing a multipart request). But that wouldn't be very useful because you'd have to check the type of each value.
It makes much more sense as a developer to specify exactly what you need. That's why @RequestParam
and @RequestPart
are available.
Because the files are not the request body, they are part of it and there is no built-in HttpMessageConverter that can convert the request to an array of MultiPartFile.
Thats why it works @RequestParam("file") MultipartFile[] files
instead of
@RequestBody MultipartFile file
Hope it helps.
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