添加maven依赖
<dependency>
<groupId>org.hibernate.validator</groupId>
<artifactId>hibernate-validator</artifactId>
</dependency>
FileCheckValid 文件校验实现类
import org.springframework.web.multipart.MultipartFile;
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.util.Arrays;
public class FileCheckValid implements ConstraintValidator<FileCheck, MultipartFile> {
String[] type;
@Override
public void initialize(FileCheck fileCheck) {
type = fileCheck.type();
}
@Override
public boolean isValid(MultipartFile value, ConstraintValidatorContext context) {
final String name = value.getOriginalFilename();
final long size = value.getSize();//bit
final long mbSize = size / 1024 / 1024;//mb
return name != null && Arrays.stream(type).anyMatch(name::endsWith);
}
}
FileCheck 文件校验注解
import javax.validation.Constraint;
import javax.validation.Payload;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target({ElementType.FIELD, ElementType.PARAMETER})
@Retention(RetentionPolicy.RUNTIME)
@Constraint(validatedBy = {FileCheckValid.class})
public @interface FileCheck {
String message() default "错误的文件类型";
String[] type() default {"xlsx", "xls", "rdf"};
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
}
DemoController.java 文件校验controller
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import javax.validation.Valid;
@RestController
@Validated
public class DemoController {
@PostMapping
public String testValidated(@RequestParam("name") String name, @RequestPart("file") @Valid @FileCheck(type = {"mdj"}) MultipartFile file) {
return file.getOriginalFilename();
}
}