自定义MultipartFile的约束验证注解

huangapple go评论80阅读模式
英文:

Custom constraint validation annotation for MultipartFile

问题

我正在尝试创建一个注解来验证控制器参数上的MultipartFile列表,但似乎没有任何效果。没有抛出异常,没有任何错误。

我查看了一些类似的问题,但没有起作用。

  • 接口:

    @Target(ElementType.PARAMETER)
    @Retention(RetentionPolicy.RUNTIME)
    @Constraint(validatedBy = {ImageValidator.class})
    public @interface ValidImage {
      String message() default "Invalid image file";
    
      Class<?>[] groups() default {};
    
      Class<? extends Payload>[] payload() default {};
    }
    
  • 类:

    public class ImageValidator implements ConstraintValidator<ValidImage, List<MultipartFile>> {
    
      @Override
      public boolean isValid(
          List<MultipartFile> listMultipartFile, ConstraintValidatorContext context) {
    
        for (var multipartFile : listMultipartFile) {
          var contentType = multipartFile.getContentType();
          if (!isSupportedContentType(contentType)) {
            context.disableDefaultConstraintViolation();
            context
                .buildConstraintViolationWithTemplate("Only JPG and PNG images are allowed.")
                .addConstraintViolation();
            return false;
          }
        }
    
        return true;
      }
    
      private boolean isSupportedContentType(String contentType) {
        var supportedContents = List.of("image/jpg", "image/jpeg", "image/png");
        return supportedContents.contains(contentType);
      }
    }
    
  • 使用:

    @PostMapping(value = "images")
      public ResponseEntity<List<ExerciseImageDTO>> uploadImages(
          @RequestParam(value = "images", required = true) @ValidImage List<@Valid MultipartFile> images) {
    
        .......
        return ResponseEntity.ok(createdImages);
      }
    
英文:

I'm trying to make an annotation to validate a list of MultipartFile on the controller parameters, but it doesn't seem to make any effect. No exception is thrown, not error at all.
I looked at some similar questions but it didn't work.

  • Interface:

    @Target(ElementType.PARAMETER)
    @Retention(RetentionPolicy.RUNTIME)
    @Constraint(validatedBy = {ImageValidator.class})
    public @interface ValidImage {
      String message() default &quot;Invalid image file&quot;;
    
      Class&lt;?&gt;[] groups() default {};
    
      Class&lt;? extends Payload&gt;[] payload() default {};
    }
    
  • Class:

    public class ImageValidator implements ConstraintValidator&lt;ValidImage, List&lt;MultipartFile&gt;&gt; {
    
      @Override
      public boolean isValid(
    	  List&lt;MultipartFile&gt; listMultipartFile, ConstraintValidatorContext context) {
    
    	for (var multipartFile : listMultipartFile) {
    	  var contentType = multipartFile.getContentType();
    	  if (!isSupportedContentType(contentType)) {
    		context.disableDefaultConstraintViolation();
    		context
    			.buildConstraintViolationWithTemplate(&quot;Only JPG and PNG images are allowed.&quot;)
    			.addConstraintViolation();
    		return false;
    	  }
    	}
    
    	return true;
      }
    
      private boolean isSupportedContentType(String contentType) {
    	var supportedContents = List.of(&quot;image/jpg&quot;, &quot;image/jpeg&quot;, &quot;image/png&quot;);
    	return supportedContents.contains(contentType);
      }
    }
    
  • Usage:

    @PostMapping(value = &quot;images&quot;)
      public ResponseEntity&lt;List&lt;ExerciseImageDTO&gt;&gt; uploadImages(
    	  @RequestParam(value = &quot;images&quot;, required = true) @ValidImage List&lt;@Valid MultipartFile&gt; images) {
    
    	.......
    	return ResponseEntity.ok(createdImages);
      }
    

答案1

得分: 1

你的控制器类上需要添加@Validated,就像这样:

@Controller
@Validated
public class SampleController {

  @PostMapping(value = "images")
  public ResponseEntity<List<ExerciseImageDTO>> uploadImages(
    @RequestParam(value = "images", required = true) @ValidImage List<@Valid MultipartFile> images) {
      .......
      return ResponseEntity.ok(createdImages);
  }

}
英文:

you need @Validated on your controller class like this

    @Controller
    @Validated
    public class SampleController {

      @PostMapping(value = &quot;images&quot;)
      public ResponseEntity&lt;List&lt;ExerciseImageDTO&gt;&gt; uploadImages(
      @RequestParam(value = &quot;images&quot;, required = true) @ValidImage List&lt;@Valid MultipartFile&gt; images) {
        .......
        return ResponseEntity.ok(createdImages);
      }

    }

huangapple
  • 本文由 发表于 2020年10月22日 08:17:17
  • 转载请务必保留本文链接:https://go.coder-hub.com/64473473.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定