Why can't we get file data from RequestBody in java?

I am trying to upload a file to the server, so I am trying to use @RequestBody to get the data from the file, but I get an error code 415 when I try to upload the file.

So, I have googled (obtained a solution for downloading a file) and found out that I can not get the file data from the request body. Therefore, I want to know why we cannot access data files from the request body, since the data will be sent to the request body in HTTP requests, so I want to know how the request occurs when the file is downloaded.

My server code before:

@RequestMapping(value = "/upload",headers = "Content-Type=multipart/form-data", method = RequestMethod.POST) @ResponseBody public String upload(@RequestBody MultipartFile file) { } 

Decision:

 @RequestMapping(value = "/upload",headers = "Content-Type=multipart/form-data", method = RequestMethod.POST) @ResponseBody public String upload(MultipartHttpServletRequest request) { } 
+7
spring-mvc file-upload
source share
2 answers

Technically, you can write your own HttpMessageConverter that will analyze the complete multiprocessor request body, but you must have a very specific type of target that can handle all parts.

You can notice from javadoc @RequestBody

Annotations indicating a method parameter must be bound to the body of the web request.

that the goal is to relate the entirety of the request body to the method parameter. How do you bind each part of a multi-page request with one parameter? Something like MultiValueMap<String, Object> ( which is used by FormHttpMessageConverter when writing a multi-user request ). But this is not very useful, because you will need to check the type of each value.

The developer makes much more sense to indicate exactly what you need. @RequestParam and @RequestPart are available for this.

+5
source share

Since files are not the body of the request, they are part of it, and there is no built-in HttpMessageConverter that can convert the request to an array of MultiPartFile. That's why it works @RequestParam("file") MultipartFile[] files

instead

 @RequestBody MultipartFile file 

Hope this helps.

+4
source share

All Articles