返回顶部
首页 > 资讯 > 后端开发 > Python >SpringBoot 上传文件判空以及格式检验流程
  • 806
分享到

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

2024-04-02 19:04:59 806人浏览 薄情痞子

Python 官方文档:入门教程 => 点击学习

摘要

目录加入依赖创建自定义注解以及实现类全局异常处理使用示例结果展示基于jsr303 通过自定义注解实现,实现思路: 存在一些瑕疵,后续补充完善。 加入依赖 部分版本已不默认自动引入该

基于jsr303 通过自定义注解实现,实现思路:

存在一些瑕疵,后续补充完善。

加入依赖

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

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

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

目录结构:

  • FileNotEmpty 自定义注解
  • FileNotEmptyValidator 单文件校验
  • FilesNotEmptyValidator 多文件校验

@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 {
    
    String message() default "文件格式不正确";
    
    Class<?>[] groups() default {};
    
    Class<? extends Payload>[] payload() default {};
    
    String[] fORMat() default {};
    
    boolean required() default true;

public class FileNotEmptyValidator implements ConstraintValidator<FileNotEmpty, MultipartFile> {
    private Set<String> formatSet = new HashSet<>();
    private boolean required;
    @Override
    public void initialize(FileNotEmpty constraintAnnotation) {
        String[] format = constraintAnnotation.format();
        this.formatSet = new HashSet<>(Arrays.asList(format));
        this.required = constraintAnnotation.required();
    }
    @Override
    public 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;
    }
}

public class FilesNotEmptyValidator implements ConstraintValidator<FileNotEmpty, MultipartFile[]> {
    private Set<String> formatSet = new HashSet<>();
    private boolean required;
    @Override
    public void initialize(FileNotEmpty constraintAnnotation) {
        String[] format = constraintAnnotation.format();
        this.formatSet = new HashSet<>(Arrays.asList(format));
        this.required = constraintAnnotation.required();
    }
    @Override
    public 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;
    }
}

全局异常处理


@ControllerAdvice
public class ExceptionHandle {
    private final static Logger logger = LoggerFactory.getLogger(ExceptionHandle.class);
       
    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public 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());
    }    
}

使用示例


@RestController
@Validated
@RequestMapping("/annex")
public class AnnexController {
 @Resource
 private IAnnexService annexService;
   
    @PostMapping(value = "/upload1")
    public Result<String> upload(@Valid AnnexUploadDTO uploadDTO) {
        return Boolean.TRUE.equals(annexService.upload(uploadDTO)) ? ResultUtil.success() : ResultUtil.fail();        
    }
    
   
    @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();
    }
    
	@Data
	static class AnnexUploadDTO{ 
	    @FileNotEmpty(format = {"pdf","doc","zip"}, message = "文件为pdf/doc/zip格式")
	    private MultipartFile[] file;
    }
}

结果展示

以上为个人经验,希望能给大家一个参考,也希望大家多多支持编程网。

--结束END--

本文标题: SpringBoot 上传文件判空以及格式检验流程

本文链接: https://lsjlt.com/news/143739.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

猜你喜欢
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作