×

Simple Multi-File Uploads With Paperclip

PaperClip

Published: February 1, 2013

I needed to add multi-file uploads to a rails application recently and was looking for a solution that didn't involve using swfupload or anything like that. I was already using paperclip and I wanted something that was super easy to get running so I went with HTML5 multi-uploads.

I use a dedicated Document model, depending on how paperclip is setup on your models, you may get different results, or this might not work for you.

First add a new file form field.

  <%= form_for Document.new, :url => documents_path, :remote => true, :html => {:multipart => true} do |f| %>
        <%= f.file_field :filearrays, :multiple =>:true %>
        <%= f.submit "Submit" %>
    <% end %>

Then in the controller create action you can do.

params[:document][:filearrays].each do |file|
  @document = Document.new(:document => file)
  @document.save
end

It will handle single files or multiples just fine.

That should be pretty much all you need to get started. Of course you can improve it by adding some validation to allowed file types, setting a flash message to let the user know if the file was uploaded or not, or anything else you may need.