当前位置: 首页 > 知识库问答 >
问题:

Spring ConstraintValidator vs MultipartFile

公西翼
2023-03-14

我想在上传使用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();
    }
}

类上传文件类型验证器:

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个答案

艾泰
2023-03-14

问题解决了。Spring试图在错误响应中序列化多部分文件

@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()));
    }
}
 类似资料:

相关问答

相关文章

相关阅读