swagger - 如何在 Swagger (OpenAPI) 中发布文件?

标签 swagger swagger-ui openapi

我正在使用 Swagger 来记录我的 REST 服务。我的一项服务需要上传 CSV 文件。我将以下内容添加到 JSON API 定义中的 parameters 部分:

{
       "name": "File",
       "description": "The file in zip format.",
       "paramType": "body",
       "required": true,
       "allowMultiple": false,
       "dataType": "file"
}

现在我在 Swagger UI 页面上看到文件上传选项。但是当我选择一个文件并单击“尝试一下”时,出现以下错误:

NS_ERROR_XPC_BAD_OP_ON_WN_PROTO: Illegal operation on WrappedNative prototype object in jquery-1.8.0.min.js (line 2)

该页面正在持续处理,但我没有收到任何响应。

有什么想法可能是错误的吗?

最佳答案

OpenAPI 规范 2.0

在 Swagger 2.0 ( OpenAPI Specification 2.0 ) 中,使用表单参数 (in: formData),并将 type 设置为 file。此外,操作的consumes必须是multipart/form-data

  consumes:
    - multipart/form-data
  parameters:
    - name: file
      in: formData   # <-----
      description: The uploaded file data
      required: true
      type: file     # <-----

OpenAPI 规范 3.0

OpenAPI Specification 3.0 ,文件被定义为二进制字符串,即类型:字符串 + 格式:二进制(或格式:字节,具体取决于用例)。文件输入/输出内容使用与任何其他模式类型相同的语义进行描述(与 OpenAPI 2.0 不同):

多部分请求,单个文件:

requestBody:
  content:
    multipart/form-data:
      schema:
        type: object
        properties:
          # 'file' will be the field name in this multipart request
          file:
            type: string
            format: binary

多部分请求,文件数组(Swagger UI 3.26.0+ 和 Swagger Editor 3.10.0+ 支持):

requestBody:
  content:
    multipart/form-data:
      schema:
        type: object
        properties:
          # The property name 'file' will be used for all files.
          file:
            type: array
            items:
              type: string
              format: binary

直接POST/PUT文件(请求体为文件内容):

requestBody:
  content:
    application/octet-stream:
      # any media type is accepted, functionally equivalent to `*/*`
      schema:
        # a binary file of any type
        type: string
        format: binary

注意:语义与其他 OpenAPI 3.0 架构类型相同:

# content transferred in binary (octet-stream):
schema:
  type: string
  format: binary

更多信息:

关于swagger - 如何在 Swagger (OpenAPI) 中发布文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14455408/

相关文章:

Java JAX-RS REST 服务客户端代码生成

java - 使用 openapi 3.0、aws-cognito oauth2 配置 Springboot 时遇到问题

c# - 使用 Swagger 的 Web API

c# - 是否可以自定义 Swagger Schema?

java - Swagger UI 仅显示获取端点。

java - 如何自定义请求正文的示例值并使用 springdoc-open-api 在 swagger-ui 上执行它

swagger - 如何在 OpenAPI (Swagger) 中指定默认的 XML 元素文本?

java - 定义常见的swagger注解

java - Swagger/Openapi 和 openapi-generator 我们在哪里添加业务逻辑代码?

python - Flagger - 添加不记名授权