Reputation: 6349
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)
{
}
Upvotes: 7
Views: 10171
Reputation: 280102
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.
Upvotes: 6
Reputation: 755
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.
Upvotes: 5