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{
    // ...
}
相关推荐
YongGit12 分钟前
探索 AI + MCP 渲染前端 UI
前端·后端·node.js
述雾学java13 分钟前
Spring Cloud Feign 整合 Sentinel 实现服务降级与熔断保护
java·spring cloud·sentinel
保持学习ing14 分钟前
苍穹外卖day3--公共字段填充+新增菜品
java·阿里云·实战·springboot·前后端·外卖项目·阿里云文件存储
77qqqiqi32 分钟前
正则表达式
java·后端·正则表达式
慧一居士1 小时前
<script setup>中的setup作用以及和不带的区别对比
前端
厦门德仔1 小时前
【WPF】WPF(样式)
android·java·wpf
大春儿的试验田1 小时前
高并发收藏功能设计:Redis异步同步与定时补偿机制详解
java·数据库·redis·学习·缓存
Gappsong8741 小时前
【Linux学习】Linux安装并配置Redis
java·linux·运维·网络安全
hqxstudying1 小时前
Redis为什么是单线程
java·redis
@大迁世界1 小时前
AR 如何改变我们构建网站的方式
后端·ar·restful