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

Spring Boot中Swagger实现含Long与MultipartFile的对象文件上传方案

解决方案

1. 给请求类和控制器补全必要注解

修改请求类 BankFileUploadRequest

要让Swagger识别请求对象并正确渲染文件上传控件,需要给类和字段添加Swagger的@Schema注解,其中MultipartFile字段必须指定格式为binary:

@AllArgsConstructor
@Getter
@Schema(description = "银行文件上传请求参数")
public class BankFileUploadRequest {

    @NotNull(message = "{validation.bankFileRequestModel.bankAccountId.null}")
    @Schema(description = "银行账户ID", example = "123")
    private final Long bankAccountId;

    @NotNull(message = "{validation.bankFileRequestModel.file.null}")
    @Schema(description = "待上传的文件", type = "string", format = "binary")
    private final MultipartFile file;

}

调整控制器方法

控制器方法参数必须添加@ModelAttribute,确保Spring能将multipart表单数据正确绑定到BankFileUploadRequest对象;同时添加@ParameterObject告诉Swagger这是一个表单参数对象:

@PostMapping(path = "/", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
@Operation(summary = "上传银行文件")
public void uploadFile(@Validated @ModelAttribute @ParameterObject BankFileUploadRequest request) {
    // 业务逻辑实现
}

2. 确保Swagger依赖配置正确

如果你用SpringDoc OpenAPI 3(推荐,替代旧版Springfox)

Maven项目在pom.xml中添加依赖:

<dependency>
    <groupId>org.springdoc</groupId>
    <artifactId>springdoc-openapi-starter-webmvc-ui</artifactId>
    <version>2.2.0</version> <!-- 使用最新稳定版即可 -->
</dependency>

Gradle项目在build.gradle中添加:

implementation 'org.springdoc:springdoc-openapi-starter-webmvc-ui:2.2.0'

要是仍在使用Springfox Swagger 2

先添加依赖:

<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-boot-starter</artifactId>
    <version>3.0.0</version>
</dependency>

然后给请求类的file字段替换为@ApiParam注解:

@ApiParam(value = "待上传的文件", required = true)
private final MultipartFile file;

控制器方法参数保留@ModelAttribute,同时配置Docket启用multipart支持(未配置过的话):

@Bean
public Docket api() {
    return new Docket(DocumentationType.SWAGGER_2)
            .select()
            .apis(RequestHandlerSelectors.basePackage("你的控制器所在包路径"))
            .paths(PathSelectors.any())
            .build()
            .apiInfo(new ApiInfoBuilder().title("API文档").build());
}

3. 验证效果

启动应用后,访问对应Swagger UI地址:

  • SpringDoc默认地址:http://localhost:8080/swagger-ui/index.html
  • Springfox默认地址:http://localhost:8080/swagger-ui.html

找到上传接口后,会看到:

  • 用于输入bankAccountId的文本框
  • 文件选择控件
  • 提交按钮,且自定义的Spring校验规则会正常生效

内容的提问来源于stack exchange,提问作者Amir Pashazadeh

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.05 15:43:42