2

Possible Duplicate:
Spring MultipartFile validation and conversion

I need to check whether file has been provided by user from jsp page.

The codes are as follows.

When I run in debug mode the file(MultiPartFile) is not null, though the file was not provided.

I want to use annotation based validation for everything.

Any help would be appreciated.

    <form:form modelAttribute="timeStampIssueParam"
        action="${pageContext['request'].contextPath}/timestamp/issue"
        method="post" enctype="multipart/form-data">
        <fieldset>
            <p>
                <form:label for="file" path="file">PDF Original</form:label>
                <br />
                <form:input path="file" type="file"/>
            </p>
            <p>



    @NotNull
    private List<MultipartFile> file

    public void issue(HttpServletResponse response, @Valid TimeStampIssueParam tsIssueParam, BindingResult result) throws JsonGenerationException, JsonMappingException, IOException {
Community
  • 1
  • 1
tompal18
  • 1,164
  • 2
  • 21
  • 39

1 Answers1

1

I think there is no build in validator for this purpose. So you need to build your own:

@Target({ METHOD, FIELD, ANNOTATION_TYPE, CONSTRUCTOR, PARAMETER })
@Retention(RUNTIME)
@Constraint(validatedBy = { OneFileItemValidator.class })
@Documented
public @interface OneFileItem {

    String message() default "{OneFileItem.message}";

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

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

The validator:

public class OneFileItemValidator
       implements ConstraintValidator<OneFileItem, List<MultipartFile>> {

    @Override
    public void initialize(final OneFileItem constraintAnnotation) {
    }

    @Override
    public boolean isValid(final List<MultipartFile> value, final ConstraintValidatorContext context) {

         //Ignore null values like the most other validators
         if (value == null) return true;

         int foundCounter = 0;
         for (MultipartFile multipartFile : value) {
            if (multipartFile.getSize() > 0) 
               foundCounter++);                
        }
        return foundCounter == 1;
    }
}

Usage:

/** Command Object / Form Backing Class */
class TimeStampIssueParam {

    @NotNull
    @OneFileItem
    private List<MultipartFile> file;

}

I have written this without an IDE, so there is maybe some syntax error in it.

Adam Gent
  • 47,843
  • 23
  • 153
  • 203
Ralph
  • 118,862
  • 56
  • 287
  • 383