I have a Spring MVC application with a file upload form.
I would like to be able to display validation errors to a user if the upl
I got the answer to my question Spring community forums:
Here is the controller method:
@RequestMapping(method = RequestMethod.POST)
public String processUploadWithModelAttribute(@ModelAttribute("myModelAttribute") final MyModelAttribute myModelAttribute, final BindingResult result, final Model model) throws IOException {
String mimeType = determineMimeType(myModelAttribute.getFile().getBytes());
if (mimeType.equalsIgnoreCase("application/pdf")){
result.addError(new ObjectError("file", "pdf not accepted"));
}
return "fileupload";
}
And the model attribute class:
public class MyModelAttribute {
private MultipartFile file;
public MultipartFile getFile() {
return file;
}
public void setFile(MultipartFile file) {
this.file = file;
}
}
The idea is to put the MultipartFile into the ModelAttribute as an attribute.