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

Spring Cloud Feign上传视频时接收端@RequestPart获取的file为null如何解决?

Feign上传文件@RequestPart参数为null解决方案

修复步骤

  • 移除第二个服务上传接口多余的consumes配置

    你当前第二个服务的上传接口同时配置了JSON和表单数据两种接收类型,会导致Spring请求解析器无法正确识别multipart格式的请求,最终文件参数被解析为null,修改为仅接收表单数据即可:

    @PostMapping(value = "/upload", consumes = {MediaType.MULTIPART_FORM_DATA_VALUE})
    public @ResponseBody Map<String, Object> uploadFile(@RequestPart("file") final MultipartFile file,
                                           @RequestParam("id") final String id,
                                           @RequestParam("ids") final String ids,
                                           @RequestParam("name") final String name
                                        ) throws IOException {
        return uploadService.uploadFile(id, ids, name, file);
    }
    
  • 修正MockMultipartFile的Content-Type参数

    构造MockMultipartFile时第三个参数为文件本身的MIME类型,而非请求的multipart/form-data类型,错误的类型会导致Feign编码器无法正确处理文件参数,修改示例:

    // 不确定文件类型时可传通用二进制流类型,视频文件可对应传video/mp4等具体类型
    final MultipartFile multipartFile = new MockMultipartFile(file.getName(), file.getName(),
            MediaType.APPLICATION_OCTET_STREAM_VALUE, IOUtils.toByteArray(inputStream));
    
  • 配置Feign表单编码器

    首先确认第一个服务已引入Feign表单依赖(Maven示例):

    <dependency>
        <groupId>io.github.openfeign.form</groupId>
        <artifactId>feign-form</artifactId>
        <version>3.8.0</version>
    </dependency>
    <dependency>
        <groupId>io.github.openfeign.form</groupId>
        <artifactId>feign-form-spring</artifactId>
        <version>3.8.0</version>
    </dependency>
    

    新增Feign配置类指定表单编码器:

    @Configuration
    public class FeignMultipartConfig {
        @Bean
        public Encoder feignFormEncoder(ObjectFactory<HttpMessageConverters> messageConverters) {
            return new SpringFormEncoder(new SpringEncoder(messageConverters));
        }
    }
    

    在Feign客户端注解中关联该配置:

    @FeignClient(name = "video-service", url = "${video-service.ribbon.listOfServers}", configuration = FeignMultipartConfig.class)
    public interface VideoServiceFeign {
        // 原有方法保持不变
    }
    
  • 调整大文件上传阈值

    SpringBoot默认单文件上传上限为1MB,超过阈值会直接丢弃文件参数,需要在两个服务的配置文件中都调整大小限制(yml示例):

    spring:
      servlet:
        multipart:
          max-file-size: 1024MB # 单文件最大大小,按需调整
          max-request-size: 1024MB # 整个请求最大大小,按需调整
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.12 11:21:02