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

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.18 16:03:12