在同一请求中上传多个文件

时间:2015-03-30 14:52:46

标签: grape grape-api

我需要创建一个POST,我可以在同一个请求中上传多个文件,但我不知道如何用葡萄写这个。现在只上传一个文件,这就是我正在做的事情,并且工作正常:

desc 'Creates a new attachment.'
params do
  requires :file, :type => Rack::Multipart::UploadedFile, :desc => "Attachment File."
end
post do
  attachment = Attachment.new
  attachment.file = ActionDispatch::Http::UploadedFile.new(params[:file])
  attachment.save!
  attachment
end

Swagger告诉我这个:

enter image description here

我在考虑做这样的事情:

desc 'Creates a new attachment.'
params do
  requires :file, :type => Array[Rack::Multipart::UploadedFile], :desc => "Attachment File."
end

但看起来不太好看:

enter image description here

我也试过了:

params do
  optional :attachments, type: Array do
  requires :file, :type => Rack::Multipart::UploadedFile, :desc => "Attachment File."
  end
end

也不是一个好结果。

enter image description here

处理此问题的正确方法是什么?

1 个答案:

答案 0 :(得分:9)

经过一些测试后,我找到了答案,我将其留在这里:

params do
  requires :first_name, type: String, desc: "User first name"
  requires :last_name, type: String, allow_blank: false, desc: "User last name"
  optional :attachments, type: Array do
    requires :file, :type => Rack::Multipart::UploadedFile, :desc => "Profile pictures."
  end
end

你不能使用招摇(或者至少我没有找到办法)来测试这个,但你可以使用这个卷曲:

curl -v -F "first_name=John" -F "last_name=McTest"  -F "attachments[][file]=@first_picture.png" -F "attachments[][file]=@second_picture.jpg" http://url/api/users