简体   繁体   中英

Custom constraint validation annotation for MultipartFile

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

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

    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM