Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Uploading multiple files in the same request

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?

like image 553
Andres Avatar asked Mar 30 '15 14:03

Andres


1 Answers

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
like image 77
Andres Avatar answered Nov 02 '22 09:11

Andres