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{
    // ...
}
相关推荐
一水鉴天1 天前
整体设计 定稿 之22 dashboard.html 增加三层次动态记录体系仪表盘 之1
前端·html
曼巴UE51 天前
UE C++ 字符串的操作
java·开发语言·c++
凛_Lin~~1 天前
安卓/Java语言基础八股文
java·开发语言·安卓
老华带你飞1 天前
出行旅游安排|基于springboot出行旅游安排系统(源码+数据库+文档)
java·数据库·vue.js·spring boot·后端·spring·旅游
张拭心1 天前
程序员越想创业,越不要急着动手
前端·人工智能
舒一笑1 天前
在低配云服务器上实现自动化部署:Drone CI + Gitee Webhook 的轻量级实践
前端·后端·程序员
龙国浪子1 天前
从零到一:打造专业级小说地图设计工具的技术实践
前端·electron
nvvas1 天前
Java AI开发入门指南
java·人工智能
元亓亓亓1 天前
考研408--操作系统--day8--操作系统--虚拟内存&请求分页&页面置换/分配
android·java·开发语言·虚拟内存
m0_740043731 天前
SpringBoot快速入门01- Spring 的 IOC/DI、AOP,
spring boot·后端·spring