Reputation: 133
I have a class:
public class user{
private String id;
private MultiPartFile file;
**Getters And Setters**
}
And in the Controller:
@PostMapping(value="/upload)
public void upload(User user){
}
In the front end I post data with form-data.I can get the user object.
But when I add @RequestBody
and @RequestParam
,it can't works.
in my opinion,@RequestParam
is used to binding parameter to simple class . when I use @RequestBody
,spring will find HttpMessageConverter
to convert http request body
to class.But I'm not sure about that.Does anyone can explain to me?
Upvotes: 0
Views: 415
Reputation: 961
So, I believe we are talking about org.springframework.web.multipart.MultipartFile
, which is to be used together with @RequestParam
variable. The mechanism is somewhat special in this case.
I had a similar problem, and what I ended up using was org.springframework.web.multipart.commons.CommonsMultipartResolver
. From frontend I've constructed multipart request with two parts, in your scenario it could be user
(containing just JSON data) and file
(containing the file itself), e.g.:
@PostMapping(value="/upload")
public void upload(@RequestParam("user") User user, @RequestParam("file") MultipartFile file){
...
}
But then, you need to configure custom serialization of the User
part, which can be done using org.springframework.web.multipart.commons.CommonsMultipartResolver
. You can configure it using bean config like this:
@Configuration
public class MappingConfig {
@Order(Integer.MIN_VALUE)
@Bean(name = "multipartResolver")
public CommonsMultipartResolver multipartResolver() {
return new CommonsMultipartResolver();
}
@Bean
public Converter<String, User> stringToUser() {
return new Converter<String, User>() {
@Override
public User convert(String jsonString) {
return new Gson().fromJson(jsonString, User.class);
}
};
}
...
}
Also, as you can see I am using Gson
manually, I couldn't find a better way how to do it. Also, it doesn't play with Java 8 lambdas, so it cannot be shortened (because of explicit types are needed for it to work).
I hope that this will at least points you to a right path.
Upvotes: 1