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

使用@rtk-query/codegen-openapi,如何自动为文件上传端点添加formData: true?

解决@rtk-query/codegen-openapi自动添加formData: true的问题

有两种可靠方式实现自动为文件上传端点添加formData: true标识:

1. 依赖OpenAPI规范自动识别

如果你的OpenAPI文档已经正确标记了文件上传的请求体类型,代码生成工具会自动处理:

  • 确保文件上传接口的请求体使用multipart/form-data作为content类型,且schema中包含format: binary的字段,示例OpenAPI定义如下:
paths:
  /files/upload:
    post:
      requestBody:
        content:
          multipart/form-data:
            schema:
              type: object
              properties:
                file:
                  type: string
                  format: binary

这种情况下,生成的代码会自动在对应端点的query配置中加入formData: true,无需额外手动配置。

2. 用transformer配置自定义处理

如果OpenAPI文档标记不明确,或者需要针对性指定端点,可以通过工具的transformer配置项修改生成逻辑:
在代码生成配置文件(如codegen.config.ts)中添加transformer函数,匹配目标端点并注入formData: true:

import type { CodegenConfig } from '@rtk-query/codegen-openapi';

const config: CodegenConfig = {
  schemaFile: './openapi.json',
  apiFile: './src/app/api/baseApi.ts',
  apiImport: 'baseApi',
  outputFile: './src/app/api/generatedApi.ts',
  // 其他基础配置...
  transformer: (generatedCode) => {
    Object.values(generatedCode.endpoints).forEach(endpoint => {
      // 可根据端点名称、URL路径等条件匹配
      if (endpoint.name === 'uploadFile' || endpoint.query?.url === '/files/upload') {
        endpoint.query.formData = true;
      }
    });
    return generatedCode;
  },
};

export default config;

运行代码生成命令后,目标端点的query配置会自动带上formData: true。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.01 06:32:44