class MultiPartFileValidator implements ConstraintValidator<ValidFileType, MultipartFile> {
private Set<String> allowed;
@Override
public void initialize(ValidFileType constraintAnnotation) {
allowed = Set.of(constraintAnnotation.allowed());
}
@Override
public boolean isValid(MultipartFile file, ConstraintValidatorContext context) {
return file == null || allowed.contains(file.getContentType());
}
}
@PostMapping
public void uploadFile(@Valid @ValidFileType @RequestPart MultipartFile uploadedFile) {
// if we get this far, the file that has passed validation
}
,有人指出,此验证器仅依赖可能被欺骗的标题。如果我不能依靠此标头(或文件名中的扩展名),我可以使用其他任何东西来验证更弹性的文件类型吗?
您可以为此测试Tika。需要此依赖性:
content-type
示例用法在类似的验证器中
org.apache.tika:tika-core:3.0.0