1

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 "Invalid image file";
    
      Class<?>[] groups() default {};
    
      Class<? extends Payload>[] payload() default {};
    }
    
  • Class:

    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);
      }
    }
    
  • Usage:

    @PostMapping(value = "images")
      public ResponseEntity<List<ExerciseImageDTO>> uploadImages(
          @RequestParam(value = "images", required = true) @ValidImage List<@Valid MultipartFile> images) {
    
        .......
        return ResponseEntity.ok(createdImages);
      }
    
Wall-E
  • 438
  • 1
  • 6
  • 18
  • You short of something to convert MultipartFile into images in post action. pls implement Converter to make it firstly. refer to https://stackoverflow.com/questions/7161215/spring-multipartfile-validation-and-conversion. – jacky-neo Oct 22 '20 at 01:34

1 Answers1

1

you need @Validated on your controller class like this

    @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);
      }

    }
guchuan
  • 125
  • 1
  • 10