Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring File Upload with RequestParam

According to the standard way of file uploading in spring: https://spring.io/guides/gs/uploading-files/ we shall use @RequestParam("file") MultipartFile file to receive the file uploaded from the form.

But I wonder why the annotation is "RequestParam" rather than something like "RequestBody", since in the form we specify "method=post", shouldn't the data be inside form post body?

Thanks a lot!

like image 963
Marlon Ou Avatar asked Feb 01 '26 03:02

Marlon Ou


1 Answers

To get MultipartFile in spring we either use @RequestPart or @RequestParam. These annotations are used to associate the part of a multipart/form-data request.This is written in spring docs:

public @interface RequestPart

Annotation that can be used to associate the part of a "multipart/form-data" request with a method argument. Supported method argument types include MultipartFile in conjunction with Spring's MultipartResolver abstraction, javax.servlet.http.Part in conjunction with Servlet 3.0 multipart requests, or otherwise for any other method argument, the content of the part is passed through an HttpMessageConverter taking into consideration the 'Content-Type' header of the request part. This is analogous to what @RequestBody does to resolve an argument based on the content of a non-multipart regular request.

Note that @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).

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

like image 190
Ajit Soman Avatar answered Feb 03 '26 16:02

Ajit Soman



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!