SpringDoc OpenAPI无法识别MultipartFile上传载荷问题排查咨询
Spring Boot springdoc-openapi Multipart文件上传参数识别异常修复
问题复现
现有Spring Boot 2.7.1版本项目,集成1.6.9版本springdoc-openapi-ui,编写多文件上传接口如下:
@PostMapping("/files") public ResponseEntity<?> uploadFiles( @RequestParam("file") MultipartFile[] file, String comment) throws IOException, ExecutionException, InterruptedException { log.debug("Total files to store: {}", file.length); log.debug("comment: {}", comment); fileService.storeFile(Arrays.asList(file), comment); return ResponseEntity.ok(environment.getProperty("file.upload.success")); }
尝试在@PostMapping上添加consumes = MediaType.MULTIPART_FORM_DATA_VALUE指定请求类型,仍然存在以下问题:
- Swagger UI中
MultipartFile类型参数被识别为String,MultipartFile[]类型参数被识别为String[] - 页面点击「Try it out」后,文件选择控件不出现,Execute按钮无法正常触发请求
使用的依赖配置如下:
<!-- Spring Boot 父依赖 --> <parent> <artifactId>spring-boot-starter-parent</artifactId> <version>2.7.1</version> </parent> <!-- springdoc-openapi 依赖 --> <dependency> <groupId>org.springdoc</groupId> <artifactId>springdoc-openapi-ui</artifactId> <version>1.6.9</version> </dependency>
根因
springdoc 1.6.x版本对MultipartFile类型(尤其是数组类型)的参数无法自动完成OpenAPI schema推断,必须显式声明参数的类型为二进制文件格式,才能让Swagger UI正确渲染上传控件。
修复方案
使用OpenAPI3自带的@Parameter注解,为文件参数显式声明schema类型:
多文件上传场景(MultipartFile[])
import io.swagger.v3.oas.annotations.Parameter; import io.swagger.v3.oas.annotations.media.ArraySchema; import io.swagger.v3.oas.annotations.media.Content; import io.swagger.v3.oas.annotations.media.Schema; import org.springframework.http.MediaType; // 其他import省略 @PostMapping(value = "/files", consumes = MediaType.MULTIPART_FORM_DATA_VALUE) public ResponseEntity<?> uploadFiles( @Parameter( description = "待上传文件列表", content = @Content( mediaType = MediaType.MULTIPART_FORM_DATA_VALUE, array = @ArraySchema(schema = @Schema(type = "string", format = "binary")) ) ) @RequestParam("file") MultipartFile[] file, @Parameter(description = "上传备注") String comment) throws IOException, ExecutionException, InterruptedException { log.debug("Total files to store: {}", file.length); log.debug("comment: {}", comment); fileService.storeFile(Arrays.asList(file), comment); return ResponseEntity.ok(environment.getProperty("file.upload.success")); }
单文件上传场景(MultipartFile)
@PostMapping(value = "/single-file", consumes = MediaType.MULTIPART_FORM_DATA_VALUE) public ResponseEntity<?> uploadSingleFile( @Parameter( description = "待上传文件", content = @Content( mediaType = MediaType.MULTIPART_FORM_DATA_VALUE, schema = @Schema(type = "string", format = "binary") ) ) @RequestParam("file") MultipartFile file, @Parameter(description = "上传备注") String comment) { // 业务处理逻辑 return ResponseEntity.ok().build(); }
注意:注解引用的包必须是
io.swagger.v3.oas.annotations下的对应注解,不要引用旧版Swagger2的io.swagger.annotations包下的同名注解,否则配置不会生效。
配置完成后重启服务,Swagger UI即可正确渲染文件选择框,Execute按钮可正常触发上传请求。
内容的提问来源于stack exchange,提问作者sanjeev
相关产品推荐
相关产品推荐

