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{
    // ...
}
相关推荐
大怪v1 天前
前端:人工智能?我也会啊!来个花活,😎😎😎“自动驾驶”整起!
前端·javascript·算法
我是天龙_绍1 天前
vue3 props 如何写ts,进行类型标注
前端
叫我詹躲躲1 天前
n8n 自动化工作流平台完整部署
前端·langchain·领域驱动设计
洛小豆1 天前
在Java中,Integer.parseInt和Integer.valueOf有什么区别
java·后端·面试
遂心_1 天前
为什么 '1'.toString() 可以调用?深入理解 JavaScript 包装对象机制
前端·javascript
IT_陈寒1 天前
JavaScript 性能优化:5 个被低估的 V8 引擎技巧让你的代码快 200%
前端·人工智能·后端
前端小张同学1 天前
服务器上如何搭建jenkins 服务CI/CD😎😎
java·后端
岛风风1 天前
关于手机的设备信息
前端
ytadpole1 天前
Spring Cloud Gateway:一次不规范 URL 引发的路由转发404问题排查
java·后端
ReturnTrue8681 天前
nginx性能优化之Gzip
前端