How do I display validation errors about an uploaded multipart file using Spring MVC

后端 未结 2 1637
谎友^
谎友^ 2021-01-14 06:47

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

2条回答
  •  太阳男子
    2021-01-14 06:59

    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.

提交回复
热议问题