Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using @RequestParam for multipartfile is a right way?

Tags:

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?

like image 879
Pranav C Balan Avatar asked Jul 02 '16 05:07

Pranav C Balan


People also ask

Can I use @RequestParam annotation for a post request?

I've read in this post that @RequestParam can only be used for get methods, but if I remove @RequestParam and stick with the params argument of the @PostMapping annotation it still doesn't work. I know I can use @RequestBody but I do not want to make a class just for those 4 parameters.

Can we use @RequestParam in Get method?

Using @RequestParam required=falseTo support optional query string parameters in a controller, we can use @RequestParam with required=false flag. Now, we can omit the id parameter from our request.

What is @RequestParam used for?

The @RequestParam is used to read the HTML form data provided by a user and bind it to the request parameter. The Model contains the request data and provides it to view page.

What is difference between @RequestParam and @RequestPart?

The main difference is that when the method argument is not a String or raw MultipartFile / Part , @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.


1 Answers

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).

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

like image 86
Wilson Avatar answered Sep 23 '22 20:09

Wilson