Can I use a paperclip to upload multiple files with a single input of multiple files?

So, I am using paperclip in my rails 3.1 application,

I add images to an element using relationships to have multiple images for each element.

What I would like to do is click the browse button and select multiple files using only one field. Instead, you need to show one image for each field each time.

Does anyone know how to do this, or do you have a great option for this that does not require flash plugins?

+4
source share
3 answers

I use only one controller, no associations (mine only for uploading several images to the gallery), but I managed to do what you ask. You will need to adapt it to work with your relationship, but it works fine for me (although it doesn’t work in IE), I am sure that it violates some rail conventions, although this is the only way I could build functionality.

The first step is to set the upload field to receive multiple files using the HTML5 tag:

<%= f.file_field :photo, multiple: 'multiple' %> 

Or if you use simple_form like me:

 <%= f.input :photo, input_html: { multiple: 'multiple' } %> 

The next step is to modify the create controller to accept and process multiple files. It's a bit, I'm sure some will mind, but hey, it works!

 def create params[:photo][:photo].each do |photo| @params = {} @params['photo'] = photo @photo = Photo.new(@params) if !@photo.save respond_to do |format| format.html { redirect_to new_photo_path, error: 'An error occured uploading.' } end end end respond_to do |format| format.html { redirect_to photos_path, notice: 'Photos were successfully uploaded.' } end end 

This is simpler than it sounds - for me the name of the controller is photo , as well as the name of the field that explains params[:photo][:photo] . Basically, it just takes the attribute :photo request (where the controller usually expects one file) and iterates over the files that were uploaded, creating a new photo for each and setting the photo @params attribute for each file, in turn, trying to save it as new photo and error notification, otherwise as soon as it is completed, it will be redirected to show photos.

As I said, this works great for me, and I hope this is also useful for you :)

Edit If this does not help, can you tell me why? Just ignoring the message after someone has taken the time to help will not make other people want to help you.

+6
source

Do not modify the controller, just add the name: attribute to the form field as follows:

 <%= f.input_field :photo, as: :file, multiple: true, name: 'article[photo]' %> 
+2
source

Here is how I did it:

 params[:photo][:photo].each do |photo| record = Photo.create(photo: photo) # if record.errors.any? # flash[:notice] = record.errors.full_messages.to_sentence # end end 

See this post for alternative ways to save multiple entries.

0
source

All Articles