java – 如何在Spring中的Rest中上传时验证文件类型,大小?

我正在尝试使用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中显示错误,如果它没有经过验证.

如果有任何标准方法可以进行此类验证?我是春天和休息的新手.所以有人请告诉我实现目标的方法.

最佳答案
 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

转载注明原文:java – 如何在Spring中的Rest中上传时验证文件类型,大小? - 代码日志