Spring ConstraintValidator vs MultipartFile

时间:2018-10-09 09:02:02

标签: java spring bean-validation

我想在ConstraintValidator上检查上传文件的扩展名。如果文件扩展名不是注释中指定的扩展名,则用户应获得公共约束验证错误响应。但是当发生这种异常时,就会发生

java.io.FileNotFoundException: C:\Users\Tensky\AppData\Local\Temp\tomcat.4393944258717178584.8443\work\Tomcat\localhost\ROOT\upload_a19ba701_88a1_4eab_88b7_eede3a273fe0_00000011.tmp

用户将获得“错误请求”页面

我的课程: 注释@UploadFileTypes

@Documented
@Constraint(validatedBy = UploadFileTypesValidator.class)
@Target({ElementType.FIELD, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface UploadFileTypes {

    String message() default "Example message";

    UploadFileType[] allowedTypes() default {UploadFileType.AUDIO, UploadFileType.VIDEO, UploadFileType.DOCUMENT, UploadFileType.IMAGE};

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

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

    @Documented
    @Target({ElementType.FIELD, ElementType.METHOD})
    @Retention(RetentionPolicy.RUNTIME)
    @interface List{
        UploadFileTypes[] value();
    }
}

UploadFileTypesValidator类:

public class UploadFileTypesValidator implements ConstraintValidator<UploadFileTypes, MultipartFile> {

    @Override
    public void initialize(UploadFileTypes constraintAnnotation) {
    }

    @Override
    public boolean isValid(MultipartFile value, ConstraintValidatorContext context) {
        return false; //<- always exception
    }
}

和控制器(永远不会到达,因为isValid总是返回false:

@RequestMapping(path = "/add", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
    public ResponseEntity addProperty(@Valid PropertyCreateRequest request) {
        return ResponseEntity.ok(null);
}

为什么会发生此异常以及如何避免它?

1 个答案:

答案 0 :(得分:0)

问题解决了。 Spring试图在错误响应中序列化MultipartFile

@Configuration
public class MvcConfig extends WebMvcConfigurerAdapter {
...
@Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
        Jackson2ObjectMapperBuilder builder = new Jackson2ObjectMapperBuilder();
        ...
        builder.serializers(new JsonSerializer<MultipartFile>() {
            @Override
            public Class<MultipartFile> handledType() {
                return MultipartFile.class;
            }

            @Override
            public void serialize(MultipartFile value, JsonGenerator gen, SerializerProvider serializers) throws IOException, JsonProcessingException {
                gen.writeStartObject();
                gen.writeStringField("contentType", value.getContentType());
                gen.writeStringField("filename",value.getName());
                gen.writeStringField("originalFilename", value.getOriginalFilename());
                gen.writeNumberField("size", value.getSize());
                gen.writeEndObject();
            }
        });

        converters.add(new MappingJackson2HttpMessageConverter(builder.build()));
    }
}