Using @RequestParam for multipartfile is a right way?
Solution 1
It is nothing wrong using @RequestParam
with Multipart
file.
@RequestParam annotation can also be used to associate the part of a "multipart/form-data" request with a method argument supporting the same method argument types. The main difference is that when the method argument is not a String, @RequestParam relies on type conversion via a registered Converter or PropertyEditor while @RequestPart relies on HttpMessageConverters taking into consideration the 'Content-Type' header of the request part. @RequestParam 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).
Solution 2
Both of the Annotations can be used, however, you can make your choice about them based on how they interpret arguments internally.
The Spring Docs states the difference between them very clearly:
The main difference is that when the method argument is not a String,
@RequestParam
relies on type conversion via a registered Converter orPropertyEditor
while@RequestPart
relies onHttpMessageConverters
taking into consideration 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).
Pranav C Balan
jquery, javascript, html, css, arrays, regex GITHUB : pranavcbalan pranavxc LinkedIn Facebook Twitter Mail Id : [email protected]__ Loves to solve problems, learn new things and help others.
Updated on August 23, 2020Comments
-
Pranav C Balan over 3 years
I'm developing a spring mvc application and I want to handle multipart request in my controller. In the request I'm passing
MultiPartFile
also, currently I'm using@RequestParam
to get the file parameter, the method look like,@RequestMapping(method = RequestMethod.POST) public def save( @ModelAttribute @Valid Product product, @RequestParam(value = "image", required = false) MultipartFile file) { ..... }
Above code works well in my service and the file is getting on the server side. Now somewhere I saw that in cases that file need to use
@RequestPart
annotation instead of@RequestParam
. Is there anything wrong to use@RequestParam
for file ? Or it may cause any kind of error in future?