Use @RequestParam for multipartfile - right way?

I am developing a spring mvc application and I want to handle the multipart request in my controller. In the request, I pass the MultiPartFile as well, I am currently using @RequestParam to get the paramaeter file, the method looks like

 @RequestMapping(method = RequestMethod.POST) public def save( @ModelAttribute @Valid Product product, @RequestParam(value = "image", required = false) MultipartFile file) { ..... } 

The above code works well in my service and the file gets to the server. Now I saw that in the case of a file, you must use the @RequestPart annotation instead of @RequestParam . Is there something wrong with using @RequestParam for a file? Or could this lead to any error in the future?

+7
java spring spring-boot spring-mvc multipart
source share
2 answers

There is nothing wrong with using @RequestParam with a Multipart file.

@RequestParam annotation can also be used to bind the part of the "multipart / form-data" request to a method argument that supports the same types of method arguments. The main difference is that when the method argument is not a string, @RequestParam relies on the type of conversion through the registered converter or PropertyEditor while @RequestPart relies on the HttpMessageConverters taking into account the "Content-Type" header of the request part. Probably @RequestParam for use with fields with a value-name, while @RequestPart is most likely to be used with parts containing more complex content (e.g. JSON, XML).

See http://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/web/bind/annotation/RequestPart.html

+5
source share

You can use both annotations, however you can make your choice about them based on how they interpret the internal arguments.

Spring Docs clearly defines the difference between the two:

The main difference is that when the method argument is not a string, @RequestParam relies on type conversion through a registered converter or PropertyEditor , and @RequestPart relies on HttpMessageConverters , taking into account the "Content-Type" header of the request part. @RequestPara is likely to be used with name-value form fields, while @RequestPart is likely to be used with parts containing more complex content (e.g. JSON, XML).

+1
source share

All Articles