SpringBoot项目文件上传校验(注解版)

需求

要实现了一个文件上传和验证的功能,具有以下特点:

  1. 自定义注解:`FileValidation`注解用于标记需要进行文件验证的方法。

  2. 文件验证拦截器:`FileValidationInterceptor`拦截器会在每个请求处理之前被调用。如果请求处理的方法上有`FileValidation`注解,那么拦截器会获取请求中的文件,并进行验证。

  3. 文件验证:文件验证的逻辑在`FileValidationUtils`的`validateFile`方法中实现。这个方法会检查文件的MIME类型和文件扩展名是否匹配,以及文件的内容是否符合预期的文件格式。

  4. 支持单个和多个文件上传:在`Controller`中,`upload`方法接受一个`MultipartFile`参数,表示上传的文件。在`FileValidationInterceptor`中,拦截器会检查请求中是否有名为"file"的参数,如果有,就获取这个参数并进行验证。同时,拦截器也支持多个文件上传,它会检查请求中是否有名为"files"的参数,如果有,就获取这个参数(一个文件列表),并对列表中的每个文件进行验证。

  5. 错误处理:如果文件验证失败,`validateFile`方法会抛出一个异常。在`FileValidationInterceptor`中,如果捕获到这个异常,拦截器会停止请求的处理,并返回一个错误响应。

在Spring Boot中,拦截器和注解是常用的技术,用于实现各种复杂的功能。以下代码的设计和实现都遵循了Spring Boot的最佳实践。

创建自定义注解

java 复制代码
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Target({ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface FileValidation {
}

拦截器

java 复制代码
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
    if (handler instanceof HandlerMethod) {
        HandlerMethod handlerMethod = (HandlerMethod) handler;
        FileValidation fileValidation = handlerMethod.getMethodAnnotation(FileValidation.class);
        if (fileValidation != null) {
            if (request instanceof MultipartHttpServletRequest) {
                MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
                MultipartFile file = multipartRequest.getFile("file");
                List<MultipartFile> files = multipartRequest.getFiles("files");
                if (file != null) {
                    if (file.isEmpty()) {
                        throw new RuntimeException("Invalid file");
                    }
                    validateFile(file);
                } else if (files != null && !files.isEmpty()) {
                    for (MultipartFile f : files) {
                        if (f.isEmpty()) {
                            throw new RuntimeException("Invalid file");
                        }
                        validateFile(f);
                    }
                } else {
                    throw new RuntimeException("No file or files attribute found in request");
                }
            }
        }
    }
    return true;
}

springboot注册拦截器

java 复制代码
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
public class WebConfig implements WebMvcConfigurer {

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new FileValidationInterceptor());
    }
}

controller使用方法

java 复制代码
@PostMapping("/uploadSingle")
@FileValidation
public ResponseEntity<ResponseResult<ExportResponseVo>> uploadSingle(@Param("file") MultipartFile file) throws Exception{
    // ...
}

@PostMapping("/uploadMultiple")
@FileValidation
public ResponseEntity<ResponseResult<ExportResponseVo>> uploadMultiple(@Param("files") MultipartFile[] files) throws Exception{
    // ...
}
相关推荐
從南走到北17 分钟前
JAVA国际版打车APP打车顺风车滴滴车跑腿APP源码Android+IOS+H5
android·java·ios
Java天梯之路18 分钟前
如何接收前端参数
java·后端
独自破碎E19 分钟前
从括号匹配到字符串解码:递归思想的巧妙应用
android·java·开发语言
Cobyte29 分钟前
17. Vue3 业务组件库按需加载的实现原理
前端·javascript·vue.js
忧郁的橙子.36 分钟前
二、Rabbit MQ 高级
java·开发语言
粥里有勺糖42 分钟前
视野修炼-技术周刊第127期 | Valdi
前端·javascript·github
q***57501 小时前
微服务搭建----springboot接入Nacos2.x
spring boot·微服务·架构
前端世界1 小时前
从零搭建 ASP.NET 单文件 Web 项目:一个能真用的 BookShop 管理页实战
服务器·前端·asp.net
Chan161 小时前
【 Java八股文面试 | JVM篇 内存结构、类加载、垃圾回收与性能调优 】
java·jvm·spring boot·后端·spring·idea
码上成长1 小时前
Vue Router 3 升级 4:写法、坑点、兼容一次讲透
前端·javascript·vue.js