Issue
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); }
Solution
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);
}
}
Answered By - guchuan
Answer Checked By - Willingham (JavaFixing Volunteer)