在 Spring 中以 Rest 方式上传时如何验证文件类型、大小?

How to validate file type, size while uploading in Rest in Spring?

我正在尝试使用 spring 和 Rest 实现文件上传。这是我到目前为止所做的

@RestController
@RequestMapping("/rest/upload")
public class ProfileImageUploadController {

   @Autowired
   ImageValidator imageValidator;

   @RequestMapping(value="/{userId}/image", method=RequestMethod.POST)
   public @ResponseBody String handleFileUpload(
        @PathVariable("userId") Integer userId,
        @ModelAttribute("image") SingleImageFile image,
        BindingResult result){

       MultipartFile file = image.getFile();
       imageValidator.validate(file, result);
       if(!result.hasErrors()){
           String name = file.getOriginalFilename();
           try{
               file.transferTo(new File("/home/maclein/Desktop/"+name));
               return "You have successfully uploaded " + name + "!";
           }catch(Exception e){
               return "You have failed to upload " + name + " => " + e.getMessage();
           }
       } else {
           return result.getFieldErrors().toString();
       }
   }
}

这是我的 ImageValidator

@Component
public class ImageValidator implements Validator {
   @Override
   public boolean supports(Class<?> arg0) {
       // TODO Auto-generated method stub
       return false;
   }

   @Override
   public void validate(Object uploadedFile, Errors error) {
       MultipartFile file = (MultipartFile) uploadedFile;

       if(file.isEmpty() || file.getSize()==0)
           error.rejectValue("file", "Please select a file");
       if(!(file.getContentType().toLowerCase().equals("image/jpg") 
            || file.getContentType().toLowerCase().equals("image/jpeg") 
            || file.getContentType().toLowerCase().equals("image/png"))){
           error.rejectValue("file", "jpg/png file types are only supported");
       }
   }
}

但是在通过邮递员进行测试时,如果文件是 pdf,则它以一种奇怪的方式显示错误。这是错误的字符串表示

"[Field error in object 'image' on field 'file': rejected value [org.springframework.web.multipart.commons.CommonsMultipartFile@3fc04a65]; codes [jpg/png file types are only supported.image.file,jpg/png file types are only supported.file,jpg/png file types are only supported.org.springframework.web.multipart.MultipartFile,jpg/png file types are only supported]; arguments []; default message [null]]"

我无法理解为什么错误列表长度为 4。我的动机是如果未验证则在 json 中显示错误。

是否有任何标准方法可以进行这种验证?我是 spring 和 Rest 的新手。所以有人请告诉我实现目标的方法。

 protected List<String> extractErrorMessages(BindingResult result) {
        List<String> errorMessages = new ArrayList<>();
        for (Object object : result.getAllErrors()) {
            if (object instanceof FieldError) {
                FieldError fieldError = (FieldError) object;
                errorMessages.add(fieldError.getCode());
            }
        }
        return errorMessages;
    }

看看 fieldError 方法,在你的情况下你可能应该使用 getField