You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Spring Boot实现不同Controller动态设置MultipartFile上传大小

Spring Boot 多Controller分配置MultipartFile上传大小的解决方案

问题核心

Spring Boot默认的Multipart上传配置是全局初始化的,启动时由MultipartAutoConfiguration创建的MultipartResolver是单例Bean,参数一旦固定就不会随配置类变量修改而更新,这就是你修改配置后仅变量更新但校验不生效的原因。

最优解决方案:自定义注解+切面做精准校验

放弃全局配置的动态修改思路,直接在业务层为不同Controller/接口设置独立的大小限制,灵活且易维护。

1. 定义上传限制注解

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface FileUploadLimit {
    long maxSize(); // 单位:字节
}

2. 实现切面校验逻辑

@Aspect
@Component
public class FileUploadLimitAspect {

    @Around("@annotation(limit)")
    public Object checkFileSize(ProceedingJoinPoint joinPoint, FileUploadLimit limit) throws Throwable {
        // 获取当前请求的Multipart文件
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) attributes.getRequest();
        
        // 遍历所有上传文件,校验大小
        for (String fileName : multipartRequest.getFileNames()) {
            MultipartFile file = multipartRequest.getFile(fileName);
            if (file != null && file.getSize() > limit.maxSize()) {
                throw new RuntimeException(String.format("文件大小超出限制,最大允许%.2fKB", limit.maxSize() / 1024.0));
            }
        }
        return joinPoint.proceed();
    }
}

3. 在Controller中使用注解

@RestController
@RequestMapping("/api/large")
public class LargeFileController {

    @PostMapping("/upload")
    @FileUploadLimit(maxSize = 10 * 1024 * 1024) // 10MB
    public String uploadLargeFile(@RequestParam("file") MultipartFile file) {
        // 业务逻辑实现
        return "大文件上传成功";
    }
}

@RestController
@RequestMapping("/api/small")
public class SmallFileController {

    @PostMapping("/upload")
    @FileUploadLimit(maxSize = 50 * 1024) // 50KB
    public String uploadSmallFile(@RequestParam("file") MultipartFile file) {
        // 业务逻辑实现
        return "小文件上传成功";
    }
}

支持动态修改的进阶方案

如果需要不重启应用就能调整限制大小,可以结合配置中心(或本地配置文件),通过请求路径匹配配置项:

1. 配置文件中定义各接口限制

file:
  upload:
    limits:
      /api/large/upload: 10485760  # 10MB
      /api/small/upload: 51200     # 50KB

2. 修改切面逻辑读取配置

@Aspect
@Component
public class DynamicFileUploadLimitAspect {

    @Autowired
    private Environment env;

    @Around("execution(* com.example.controller.*.*(..))")
    public Object checkDynamicFileSize(ProceedingJoinPoint joinPoint) throws Throwable {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        String requestPath = request.getRequestURI();
        
        // 读取对应路径的限制配置
        String limitConfig = env.getProperty("file.upload.limits" + requestPath);
        if (limitConfig != null) {
            long maxSize = Long.parseLong(limitConfig);
            MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
            
            for (String fileName : multipartRequest.getFileNames()) {
                MultipartFile file = multipartRequest.getFile(fileName);
                if (file != null && file.getSize() > maxSize) {
                    throw new RuntimeException(String.format("文件大小超出限制,最大允许%.2fKB", maxSize / 1024.0));
                }
            }
        }
        return joinPoint.proceed();
    }
}

修改配置文件后,下次请求就会自动应用新的限制大小,无需重启服务。

内容的提问来源于stack exchange,提问作者Teneson125

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.19 11:10:34