SpringBoot 上传文件判空以及格式检验

news/2024/10/28 22:31:37/

基于jsr303 通过自定义注解实现,实现思路:
在这里插入图片描述
存在一些瑕疵,后续补充完善。

加入依赖

部分版本已不默认自动引入该依赖,选择手动引入

        <dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-validation</artifactId></dependency>

创建自定义注解以及实现类

目录结构:

  • FileNotEmpty 自定义注解
  • FileNotEmptyValidator 单文件校验
  • FilesNotEmptyValidator 多文件校验
/*** jsr303 文件格式校验注解** @author maofs* @version 1.0* @date 2021 -11-29 10:16:03*/
@Documented
@Constraint(validatedBy = {FileNotEmptyValidator.class, FilesNotEmptyValidator.class}
)
@Target({ElementType.METHOD, ElementType.FIELD, ElementType.ANNOTATION_TYPE, ElementType.CONSTRUCTOR, ElementType.PARAMETER, ElementType.TYPE_USE})
@Retention(RetentionPolicy.RUNTIME)
public @interface FileNotEmpty {/*** Message string.** @return the string*/String message() default "文件格式不正确";/*** 校验组** @return the class [ ]*/Class<?>[] groups() default {};/*** Payload class [ ].** @return the class [ ]*/Class<? extends Payload>[] payload() default {};/*** 需要校验的格式数组** @return the string [ ]*/String[] format() default {};/*** 是否必填 为false时文件为空则不校验格式,不为空则校验格式* 为true时文件不能为空且需要验证格式** @return the boolean*/boolean required() default true;
/*** 单文件校验** @author maofs* @version 1.0* @date 2021 -11-29 10:16:03*/
public class FileNotEmptyValidator implements ConstraintValidator<FileNotEmpty, MultipartFile> {private Set<String> formatSet = new HashSet<>();private boolean required;@Overridepublic void initialize(FileNotEmpty constraintAnnotation) {String[] format = constraintAnnotation.format();this.formatSet = new HashSet<>(Arrays.asList(format));this.required = constraintAnnotation.required();}@Overridepublic boolean isValid(MultipartFile multipartFile, ConstraintValidatorContext constraintValidatorContext) {if (multipartFile == null || multipartFile.isEmpty()) {return !required;}String originalFilename = multipartFile.getOriginalFilename();assert originalFilename != null;String type = originalFilename.substring(originalFilename.lastIndexOf('.') + 1).toLowerCase();if (!formatSet.isEmpty()) {return formatSet.contains(type);}return true;}
}
/***  多文件校验** @author maofs* @version 1.0* @date 2021 -11-29 10:16:03*/
public class FilesNotEmptyValidator implements ConstraintValidator<FileNotEmpty, MultipartFile[]> {private Set<String> formatSet = new HashSet<>();private boolean required;@Overridepublic void initialize(FileNotEmpty constraintAnnotation) {String[] format = constraintAnnotation.format();this.formatSet = new HashSet<>(Arrays.asList(format));this.required = constraintAnnotation.required();}@Overridepublic boolean isValid(MultipartFile[] multipartFiles, ConstraintValidatorContext constraintValidatorContext) {if (multipartFiles == null || multipartFiles.length == 0) {return !required;}for (MultipartFile file : multipartFiles) {String originalFilename = file.getOriginalFilename();assert originalFilename != null;String type = originalFilename.substring(originalFilename.lastIndexOf('.') + 1).toLowerCase();if (formatSet.isEmpty() || !formatSet.contains(type)) {return false;}}return true;}
}

全局异常处理

/*** 统一异常处理** @author maofs* @version 1.0* @date 2021 -11-29 10:16:03*/
@ControllerAdvice
public class ExceptionHandle {private final static Logger logger = LoggerFactory.getLogger(ExceptionHandle.class);@ExceptionHandler(value = Exception.class)@ResponseBodypublic Result<String> handle(Exception e) {logger.error(e.getMessage());StringBuilder stringBuilder = new StringBuilder();             //jsr303异常if (e instanceof ConstraintViolationException) {ConstraintViolationException ex = (ConstraintViolationException)e;Set<ConstraintViolation<?>> constraintViolations = ex.getConstraintViolations();for (ConstraintViolation<?> constraintViolation : constraintViolations) {stringBuilder.append(constraintViolation.getMessageTemplate());}} else if (e instanceof BindException) {BindException bindException = (BindException)e;stringBuilder.append(bindException.getFieldErrors().stream().map(FieldError::getDefaultMessage).collect(Collectors.joining(",")));} else {stringBuilder.append("未知错误:").append("请联系后台运维人员检查处理!");           }return  ResultUtil.fail(stringBuilder.toString());}}

使用示例

/*** 文件上传示例接口** @author maofs* @version 1.0* @date 2021 -11-19 16:08:26*/
@RestController
@Validated
@RequestMapping("/annex")
public class AnnexController {@Resourceprivate IAnnexService annexService;/*** 文件上传示例1** @param uploadDTO the upload dto* @return the result*/@PostMapping(value = "/upload1")public Result<String> upload(@Valid AnnexUploadDTO uploadDTO) {return Boolean.TRUE.equals(annexService.upload(uploadDTO)) ? ResultUtil.success() : ResultUtil.fail();}/*** 文件上传示例2** @param number      项目编号* @param pictureFile 图片文件* @param annexFile   附件文件* @return result result*/@PostMapping(value = "/upload2")public Result<String> upload(@NotBlank(@FileNotEmpty(format = {"png", "jpg"}, message = "图片为png/jpg格式", required = false)MultipartFile pictureFile, @FileNotEmpty(format = {"doc", "docx", "xls", "xlsx"}, message = "附件为doc/docx/xls/xlsx格式", required = false)MultipartFile annexFile) {       return Boolean.TRUE.equals(annexService.upload( pictureFile, annexFile)) ? ResultUtil.success() : ResultUtil.fail();}@Datastatic class AnnexUploadDTO{ @FileNotEmpty(format = {"pdf","doc","zip"}, message = "文件为pdf/doc/zip格式")private MultipartFile[] file;}
}

结果展示

接口1效果展示
接口2效果展示


http://www.ppmy.cn/news/565690.html

相关文章

递归判断JS对象内所有属性值是否为空,并返回空值的key和value

递归判断JS对象内所有属性值是否为空&#xff0c;并返回空值的key和value 文章目录 递归判断JS对象内所有属性值是否为空&#xff0c;并返回空值的key和value代码测试用例运行结果&#xff1a; 代码 const paramsValidate (obj: any, ...roles: Array<Array<string>…

latex beamer 空一行_吾空X5空妖系列笔记本开启预售,支持144Hz刷新率,WiFi6,性能爆表...

在笔记本这个市场&#xff0c;细分也比较明显&#xff0c;商务本&#xff0c;轻薄本&#xff0c;游戏本&#xff0c;厂商各有专注&#xff0c;消费者也各取所需&#xff1b;近年来&#xff0c;吾空笔记本也越来越受玩家的喜欢&#xff0c;那么作为玩家的专属定制级笔记本电脑品…

让空灵占据心灵

“ 春--- 伴着雨丝来的&#xff0c;淅淅沥沥 如诗如画&#xff0c;翩然而至&#xff1b; 也是捧着雨滴走的&#xff0c; 滴滴答答&#xff0c;如泣如诉&#xff0c; 不忍离去&#xff01;” 一位诗人用这样美丽的文字&#xff0c;写出了暮春时节的真实景象&#xff0c;也写出了…

此心安处是吾乡

《定风波常羡人间琢玉郎》 苏轼 常羡人间琢玉郎&#xff0c;天教分付点酥娘。 自作清歌传皓齿&#xff0c;风起&#xff0c;雪飞炎海变清凉。 万里归来年愈少&#xff0c;微笑&#xff0c;笑时犹带岭梅香。 试问岭南应不好&#xff1f; 却道&#xff0c;此心安处是吾乡。 【…

postman 发送post请求,PHP后端接收到的数据为空

如题&#xff0c;使用postman发送请求时&#xff0c;在后端接收到的数据为空 解决方法&#xff1a; 1.Headers配置&#xff1a; 新增一个指定类型为json数据的键值对&#xff0c;即&#xff1a; Content-type : application/json;charsetutf-8 具体如下图&#xff1a; 2.B…

php empty 0问题,解析:php empty 和空字符串区别

如果 var 是非空或非零的值,则 empty() 返回 FALSE。换句话说,""、0、"0"、NULL、FALSE、array()、var $var; 以及没有任何属性的对象都将被认为是空的,如果 var 为空,则返回 TRUE。 除了当变量没有置值时不产生警告之外,empty() 是 (boolean) var 的…

对象数组空指针异常

Java中对象数组空指针异常问题 记录一个Java中遇到的问题。 在图的广度优先遍历中用到了队列&#xff0c;在类中定义的内部类&#xff0c;并且在外部类中声明了内部类的一个对象数组&#xff0c;但是在使用对象数组时一直报 NullPointerException。 部分代码如下&#xff1a; p…

java当中如何让返回值不为空?

java当中如何让返回值不为空&#xff1f;你不仅要有方法和方法体&#xff0c;还要调用&#xff0c;还要创建一个变量名&#xff0c;然后打印&#xff0c;只有这样才能让返回值不为空。这样的话&#xff0c;就不用再另外创建一个类进行测试了。其他的我都不说了&#xff0c;想必…