【问题标题】:How to upload files in grape swagger rails? (Error: The requested format 'txt' is not supported)如何在葡萄招摇导轨上上传文件? (错误:不支持请求的格式“txt”)
【发布时间】:2020-12-23 11:16:04
【问题描述】:

我需要使用 Grape UI 实现文件上传。我们有这些宝石:

gem 'grape'
gem 'grape-entity'
gem 'grape-papertrail'
gem 'grape-swagger'
gem 'grape-swagger-entity'

在我的attachments_api.rb中:

# frozen_string_literal: true

module V1
  class AttachmentsAPI < ApplicationAPI
    content_type :pdf, 'multipart/form-data'

    resource :attachments do
      desc 'Upload attchment file'
      params do
        requires :file, type: File, documentation: { param_type: 'formData', data_type: 'file' }
      end
      post do
        byebug
      end
    end
  end
end

但是当我在 UI (https://editor.swagger.io/) 中运行它时,我每次都会遇到相同的错误(我尝试附加的 txt 文件、png 或 pdf 无关紧要):

The requested format &#39;txt&#39; is not supported.

生成的json_doc看起来比较奇怪:

paths:
  /attachments:
    post:
      description: Upload attchment file
      produces:
        - application/json
      consumes:
        - application/json
      parameters:
        - in: formData
          name: file
          type: file
          required: true
      responses:
        '201':
          description: Upload attchment file
      tags:
        - attachments
      operationId: postAttachments

我不明白为什么我们会看到那里

consumes:
  - application/json

如何解决此错误并正确上传文件?感谢您的帮助!

【问题讨论】:

  • consumes 必须是 multipart/form-data。检查grape-swagger是否有一个注释来覆盖consumes值。

标签: ruby-on-rails api file-upload swagger swagger-ui


【解决方案1】:

这解决了问题:

desc 'Upload attachment file', consumes: ['multipart/form-data']

【讨论】:

    猜你喜欢
    • 2016-02-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-09-30
    • 1970-01-01
    • 1970-01-01
    • 2017-05-01
    • 1970-01-01
    相关资源
    最近更新 更多