自定义验证程序到MultipartFile

时间:2017-02-28 20:48:17

标签: spring spring-mvc spring-boot spring-validator

我正在尝试构建自定义验证程序以使用MultipartFile Spring检查Validator,但我遇到了这个问题:

 An Errors/BindingResult argument is expected to be declared immediately after the model attribute, the @RequestBody or the @RequestPart arguments to which they apply: public org.springframework.web.context.request.async.DeferredResult br.com.mobtrack.api.resource.CityResource.uploadImage(org.springframework.web.multipart.MultipartFile,org.springframework.validation.BindingResult)

这是我的Validator类:

@Component
public class MultipartFileValidator implements Validator{

    @Override
    public boolean supports(Class<?> aClass) {
        return MultipartFile.class.isAssignableFrom(aClass);
    }

    @Override
    public void validate(Object o, Errors errors) {
        MultipartFile file = (MultipartFile) o;
       if (file == null || file.isEmpty()){
           errors.reject("image","send a valid image. );
       }
    }
}

这是我的RestController

 @PostMapping("/image")
    public DeferredResult<String> uploadImage(@Valid MultipartFile image, BindingResult result) {

        if (result.hasErrors()) {
            throw new ImageNotFoundException("test");
        } else {
            DeferredResult<String> deferredResult = new DeferredResult<>();

            Thread thread = new Thread(new ImageStorageRunnable(image, deferredResult, imageStorage));
            thread.start();
            return deferredResult;
        }
    }

1 个答案:

答案 0 :(得分:0)

  

“BindingResult参数应该在模型属性,@ RequestBody或它们应用的@RequestPart参数之后立即声明”

它与验证器无关。它似乎与控制器有关。

似乎在告诉你这个问题。您需要使用@RequestBody或@RequestPart注释来告诉它在哪里查找要绑定的数据。