So I have seen examples where a MultiPartFile
type is passed in @RequestParam
and not in @RequestBody
. That seems to be a very usual way people suggest to consume a file content in a @RestController
something like this
public ResponseEntity<String> submitFile(@RequestParam(value="file") MultipartFile file)
I am wondering how is it a good practice as the file data gets passed in the url. Why not pass it in @RequestBody
instead?
So I changed the above code to something like this
public ResponseEntity<String> submitFile(@RequestBody MyCustomObj myObj)
myCustomObj
is a pojo with just one field named file of type MultipartFile
The problem is that I only have swagger and postman to test it and when I use the @RequestBody
approach, none of these would give me an option to upload a file as they would in case of passing MultipartFile
in RequestParam
.
Can someone please throw some more light on this and tell me the right way to do this?
@RequestParam maps to query parameters, form data, and parts in multipart requests and not only query parameters as mentioned the offical docs. https://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/web/bind/annotation/RequestParam.html
Files are not supposed to be sent as the request body serialized in JSON. What you should do instead is to use the content type "multipart/form-data" for your file uploads (as mentioned in the HTML 4 spec below) and in that case @RequestParam will be the appropriate annotation to use https://www.w3.org/TR/html401/interact/forms.html#h-17.13.4