Search code examples
spring-bootvalidationthymeleaf

Validate image if existing or not null only in spring boot?


I'm trying to validate image in Spring boot with a custom messages and custom validator. Here is my file path for the validator files

I just need to know how to check first if the image file is existing or not null and then validate it.

I need to mention that my image can be null value, in this case, I should not do the validation.

Here is the example for more clarification:

I first created the annotation as follows:

import javax.validation.Constraint;
import javax.validation.Payload;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
@Constraint(validatedBy = {ImageFileValidator.class})
public @interface ValidImage {
    String message() default "Invalid image file";

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

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

I've created the validator as following:

import org.springframework.web.multipart.MultipartFile;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;

public class ImageFileValidator implements ConstraintValidator<ValidImage, MultipartFile> {

    @Override
    public void initialize(ValidImage constraintAnnotation) {

    }

    @Override
    public boolean isValid(MultipartFile multipartFile, ConstraintValidatorContext context) {

        boolean result = true;

        String contentType = multipartFile.getContentType();
        if (!isSupportedContentType(contentType)) {
            context.disableDefaultConstraintViolation();
            context.buildConstraintViolationWithTemplate(
                    "Only PNG or JPG images are allowed.")
                   .addConstraintViolation();

            result = false;
        }

        return result;
    }

    private boolean isSupportedContentType(String contentType) {
        return contentType.equals("image/png")
                || contentType.equals("image/jpg")
                || contentType.equals("image/jpeg");
    }
}

Finally, applied the annotation as following:

public class CreateUserParameters {

    @ValidImage
    private MultipartFile image;
...
}

The code of the custom validator was here : File upload in Spring Boot: Uploading, validation, and exception handling by Wim Deblauwe in the last comment.


Solution

  • This is not really the answer for my question, but a temporary solution if someone has the same issue.

    So the thing is, If the image is null, I will just tell the ImageFileValidator to send True to ValidImage and then the image will be validated. Which means I don't have to send errors.

    @Override
        public boolean isValid(MultipartFile multipartFile, ConstraintValidatorContext context) {
    
            boolean result = true;
            String contentType = "";
            try {
                contentType = multipartFile.getContentType();
                if(fileNameLength(multipartFile) == 0) {
                    return result;
                }
            } catch(NullPointerException e) {
                e.printStackTrace();
                
            }
    
    if (!isSupportedContentType(contentType)) {
    .....
    

    The rest of the code can be found above. It might return NullException as well, so make sure to handle it.