如何使用Spring MVC显示有关上载的多部分文件的验证错误

bal*_*teo 3 validation multipartform-data spring-mvc multipart

我有一个带有文件上传表单Spring MVC应用程序.

如果上传的内容无效(例如内容不是图像等),我希望能够向用户显示验证错误.

然而,通过定义什么是张贴的类型是:MultipartFile(多/表单数据),因此我不能有一个@ModelAttribute在我的形式,为了使用BindingResult,看来我确实需要一个@ModelAttribute之前的BindingResult.

那么我的问题是,当我拥有验证错误时,最合适的方式是MultipartFile什么?我当然可以手动将模型属性添加到模型中,但我确信有更好的方法.

mic*_*man 6

如果您使用的是Java Bean Validation(JSR 303),则可以制作用于验证内容类型的注释.见下面的代码.

import static java.lang.annotation.ElementType.*;
import static java.lang.annotation.RetentionPolicy.*;
/**
 * The annotated element must have specified content type.
 *
 * Supported types are:
 * <ul>
 * <li><code>MultipartFile</code></li>
 * </ul>
 *
 * @author Michal Kreuzman
 */
@Documented
@Retention(RUNTIME)
@Constraint(validatedBy = {ContentTypeMultipartFileValidator.class})
@Target({ METHOD, FIELD, ANNOTATION_TYPE, CONSTRUCTOR, PARAMETER })
public @interface ContentType {

    String message() default "{com.kreuzman.ContentType.message}";

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

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

/**
 * Specify accepted content types.
 *
 * Content type example :
 * <ul>
 * <li>application/pdf - accepts PDF documents only</li>
 * <li>application/msword - accepts MS Word documents only</li>
 * <li>images/png - accepts PNG images only</li>
 * </ul>
 *
 * @return accepted content types
 */
     String[] value();
}
Run Code Online (Sandbox Code Playgroud)
/**
  * Validator of content type. This is simple and not complete implementation
  * of content type validating. It's based just on <code>String</code> equalsIgnoreCase
  * method.
  *
  * @author Michal Kreuzman
  */
 public class ContentTypeMultipartFileValidator implements ConstraintValidator<ContentType, MultipartFile> {

private String[] acceptedContentTypes;

@Override
public void initialize(ContentType constraintAnnotation) {
    this.acceptedContentTypes = constraintAnnotation.value();
}

@Override
public boolean isValid(MultipartFile value, ConstraintValidatorContext context) {
    if (value == null || value.isEmpty())
        return true;

    return ContentTypeMultipartFileValidator.acceptContentType(value.getContentType(), acceptedContentTypes);
}

private static boolean acceptContentType(String contentType, String[] acceptedContentTypes) {
    for (String accept : acceptedContentTypes) {
            // TODO this should be done more clever to accept all possible content types
        if (contentType.equalsIgnoreCase(accept)) {
            return true;
        }
    }

    return false;
}
}
Run Code Online (Sandbox Code Playgroud)
public class MyModelAttribute {

@ContentType("application/pdf")
private MultipartFile file;

public MultipartFile getFile() {
    return file;
}

public void setFile(MultipartFile file) {
    this.file = file;
}
}
@RequestMapping(method = RequestMethod.POST)
public String processUploadWithModelAttribute(@ModelAttribute("myModelAttribute") @Validated final MyModelAttribute myModelAttribute, final BindingResult result, final Model model) throws IOException {
 if (result.hasErrors()) {
     // Error handling
     return "fileupload";
 }

 return "fileupload";
}
Run Code Online (Sandbox Code Playgroud)