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

OpenAPI生成多部分多文件上传时未遵循指定字段名问题

解决OpenAPI Generator kotlin-spring生成器文件数组字段名被改为"file"的问题

我使用OpenAPI 3.0.2定义API,通过版本6.2.1的org.openapi.generator插件和kotlin-spring生成器生成Java/Kotlin代码时,遇到一个问题:Schema中名为attachments的文件数组字段,生成的代码里被替换成了@RequestPart("file"),而我需要保留原字段名attachments以兼容现有API。

问题重现的核心配置

API路径定义:

/emails/send:
  post:
    operationId: sendEmail
    requestBody:
      required: true
      content:
        multipart/form-data:
          schema:
            $ref: '#/components/schemas/EmailSendRequest'
    responses:
      "200":
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/EmailSendResponse'

请求Schema定义:

EmailSendRequest:
  type: object
  properties:
    # 其他字段省略
    attachments:
      type: array
      items:
        type: string
        format: binary

生成的代码中,该字段被错误处理为:

@Parameter(description = "file detail")  
@RequestPart("file") attachments: kotlin.collections.List<org.springframework.core.io.Resource>?

解决方案

方案1:在Schema字段中添加扩展指定请求部件名称

在attachments字段下添加x-request-part-name扩展,明确指定请求部件的名称为attachments:

attachments:
  type: array
  items:
    type: string
    format: binary
  x-request-part-name: attachments

这个扩展会直接告诉生成器,该字段对应的@RequestPart名称使用指定值,而非默认的"file"。

方案2:配置生成器保留原始参数名称

在插件配置中添加originalParameterNames=true参数,强制生成器使用Schema中定义的原始字段名作为请求部件名称。

以Gradle插件为例:

openApiGenerate {
    generatorName = "kotlin-spring"
    inputSpec = "src/main/resources/openapi.yaml"
    outputDir = "build/generated/openapi"
    configOptions = [
        originalParameterNames: "true",
        useRequestPart: "true" // 确保使用@RequestPart而非@RequestParam处理文件
    ]
}

以Maven插件为例:

<plugin>
    <groupId>org.openapi.generator</groupId>
    <artifactId>openapi-generator-maven-plugin</artifactId>
    <version>6.2.1</version>
    <executions>
        <execution>
            <goals>
                <goal>generate</goal>
            </goals>
            <configuration>
                <generatorName>kotlin-spring</generatorName>
                <inputSpec>src/main/resources/openapi.yaml</inputSpec>
                <outputDir>${project.build.directory}/generated-sources/openapi</outputDir>
                <configOptions>
                    <originalParameterNames>true</originalParameterNames>
                    <useRequestPart>true</useRequestPart>
                </configOptions>
            </configuration>
        </execution>
    </executions>
</plugin>

额外注意事项

  • 检查你的EmailSendRequest Schema中的required字段,当前定义了success和failureReason但Schema中并未包含这两个属性,这可能导致生成代码时出现警告或错误,建议修正该配置。
  • 如果使用的是较新版本的OpenAPI Generator(高于6.2.1),可以尝试升级插件版本,部分旧版本的文件字段命名问题已在后续版本中修复。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 05:01:08