Spring应用中Swagger未显示文件上传控件的问题咨询
解决Spring文件上传接口在Swagger中不显示控件的问题
核心问题修正
你的代码存在关键错误:把produces设为multipart/form-data,该属性用于定义接口返回的媒体类型,而文件上传接口需要指定的是接收的请求媒体类型,应替换为consumes。
修正后的代码示例
import io.swagger.annotations.ApiParam; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.multipart.MultipartFile; @RestController public class FileUploadController { private final FileService fileService; // 构造注入服务 public FileUploadController(FileService fileService) { this.fileService = fileService; } @PostMapping( value = "/add", consumes = "multipart/form-data" // 替换为consumes指定请求类型 ) public void addFile( @ApiParam(name = "file", value = "待上传的文件", required = true) @RequestParam("file") MultipartFile file ) throws Exception { // 可按需保留或简化异常声明 fileService.addAttachment(file); } }
额外注意事项
- 确保项目引入了适配Spring Boot版本的Swagger依赖(如Springfox或SpringDoc)。
- 若使用SpringDoc(OpenAPI 3.0),可用
@Parameter注解替代@ApiParam,效果一致:@Parameter(name = "file", description = "待上传的文件", required = true) @RequestParam("file") MultipartFile file - 检查Swagger配置类,默认配置已支持multipart类型,无需额外修改,若有自定义配置不要禁用该类型支持。
内容的提问来源于stack exchange,提问作者FischKopp
相关产品推荐
相关产品推荐

