Swagger调用SpringBoot文件上传接口提示file请求参数缺失如何解决
文件上传接口MissingServletRequestPartException报错解决方案
核心报错原因:接口期望接收名为file的文件请求参数,但请求中未传递对应名称的有效参数,可按以下步骤逐一排查修复:
- 修正接口注解参数名不匹配问题
你当前代码中@ApiParam注解的name属性配置为file-name,和@RequestParam指定的参数名file不一致,Swagger会优先按照@ApiParam的配置生成参数,导致请求传递的参数名不符合接口预期。修正后的接口代码参考:
@ApiOperation(value = "Send file", notes = "This method accept a file") @PostMapping(value = "/upload-file", consumes = MediaType.MULTIPART_FORM_DATA_VALUE) public ResponseEntity<? extends Response> writeExcelledRowColumnIntoDatabase(@ApiParam( name = "file", type = "file", value = "上传的xlsx文件", example = "file.xlsx", required = true) @RequestParam("file") MultipartFile pathFile) throws IOException { return this.userDetailService.acceptExcellFileAndInsertToDatabase(pathFile); }
- 确认Spring文件上传配置正常
如果是Spring Boot项目,检查application配置文件中是否开启了文件上传功能(默认是开启状态,若手动修改过需确认):
spring.servlet.multipart.enabled=true # 可根据需求调整文件大小限制 spring.servlet.multipart.max-file-size=10MB spring.servlet.multipart.max-request-size=20MB
如果是传统Spring MVC项目,确认已经注入MultipartResolver的Bean:
@Bean public CommonsMultipartResolver multipartResolver() { CommonsMultipartResolver resolver = new CommonsMultipartResolver(); resolver.setDefaultEncoding("UTF-8"); return resolver; }
- 修正Swagger配置(Swagger2版本适用)
如果使用Swagger2,在Docket配置类中添加MultipartFile的类型映射,避免Swagger识别文件参数异常:
@Bean public Docket api() { return new Docket(DocumentationType.SWAGGER_2) .directModelSubstitute(MultipartFile.class, ByteArrayResource.class) // 其余原有配置保持不变 .select() .apis(RequestHandlerSelectors.basePackage("你的项目业务包路径")) .paths(PathSelectors.any()) .build(); }
- 验证请求调用规范
使用Swagger调用时,直接点击参数右侧的「Choose File」按钮选择本地文件上传,不要手动填写参数值;使用Postman调用时,Body选择form-data格式,key填写file,类型选择File(不要用默认的Text类型),再选择对应文件提交。
内容的提问来源于stack exchange,提问作者iwritecomeinmymind
相关产品推荐
相关产品推荐

