Uploading multiple files in the same request
Asked Answered
G

1

8

I need to create a POST where I can upload multiple files in the same request, but I don't know how to write this with grape. Right now to upload just one file this is what I'm doing and It's working fine:

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 shows me this:

enter image description here

I was thinking of doing something like this:

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

But it's not looking fine:

enter image description here

Also I tried:

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

Not a good result either.

enter image description here

What's the right way of handling this?

Gisela answered 30/3, 2015 at 14:52 Comment(0)
G
11

After some testing I found the answer, I'll leave it here:

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

You can't test this using swagger (or at least I didn't found a way of doing it), but you can use this curl:

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
Gisela answered 1/4, 2015 at 13:59 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.