将图像作为多部分表单数据上传时对 FormDataContentDisposition 的自定义验证

Custom Validation over FormDataContentDisposition while uploading image as Multipart form data

我想验证使用 Jersey 中的多部分表单数据上传的图像的文件扩展名。
我创建了一个自定义注释 ImageExtensionValidator:

package io.gupshup.dashboard.annotations;

import static java.lang.annotation.ElementType.FIELD;
import static java.lang.annotation.ElementType.PARAMETER;
import static java.lang.annotation.RetentionPolicy.RUNTIME;

import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import java.util.regex.Pattern;

import javax.validation.Constraint;
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import javax.validation.Payload;

@Retention(RUNTIME)
@Target({ FIELD, PARAMETER })
@Constraint(validatedBy = { ImageExtensionValidator.Validator.class })
public @interface ImageExtensionValidator {

    String message() default "Please Enter valid Image";

    String url() default "";

    Class<?>[] groups() default {};

    Class<? extends Payload>[] payload() default {};

    class Validator implements ConstraintValidator<ImageExtensionValidator, String> {

        private String constraintMessage;
        private String fileName;
        Pattern pattern = Pattern.compile("\.(?:jpg|gif|png|jpeg|JPG|GIF|PNG|JPEG)");

        @Override
        public void initialize(ImageExtensionValidator constraintAnnotation) {
            constraintMessage = constraintAnnotation.message();
            fileName = constraintAnnotation.url();
        }

        @Override
        public boolean isValid(String value, ConstraintValidatorContext context) {

            if (value == null || value.trim().isEmpty()) {
                return true;
            } else if (pattern.matcher(value.trim()).matches()) {
                return true;
            } else {
                context.disableDefaultConstraintViolation();
                context.buildConstraintViolationWithTemplate(constraintMessage).addConstraintViolation();
                return false;
            }

        }
    }
}

并像这样使用它:

@FormDataParam("logo")
private InputStream logoStream;

@ImageExtensionValidator
@FormDataParam("logo")
private FormDataContentDisposition logoDetails;

我在使用时遇到以下错误:

javax.validation.UnexpectedTypeException: HV000030: No validator could be found for type: org.glassfish.jersey.media.multipart.FormDataContentDisposition.

我知道还有其他方法可以做到。但是这样的事情会让我的代码更整洁。提前致谢。

在 Paul 的评论之后,我意识到我的 ImageExtensionValidator 代码中有一个错误。 class 应定义为:

class Validator implements ConstraintValidator<ImageExtensionValidator,
                                               FormDataContentDisposition> {}