Multiple file upload with Rails 3.2, paperclip, html5 and no javascript
Today, I was looking for a simple multiple file upload solution for Ruby on Rails 3.2 with paperclip 3.0.4 and found several jQuery and Flash solutions, like Uploadify or jQuery-File-Upload, buy they seemed to be too heavy and complicated for my case. I didn’t need asynchronous upload and other features they provide, I only needed really simple (ideally pure html) solution to save several images for my Item
model with regular form submit, but with possibility to select all images at once (in one input field).
Luckily, there is html5 attribute multiple
for input type='file'
, which is already supported by modern browsers (Opera, Firefox, Chrome, Safari), and that’s pretty ok for me. In the following code snippet, I’ll show, how I used this attribute and how I marked up my rails form make it work with paperclip.
Note: As soon as IE doesn’t support multiple
attribute, the example below will allow to upload only one file for IE users.
So basically I have Item
model, which has many AttachedAsset
models. AttachedAsset
model is used to store image with paperclip. All code in models and controller is very simple and found in paperclip’s HOWTOs. The only non-obvious part is file_field_tag
in the new.html.haml
template – it has tricky name
(to be handled as array of asset
inside attached_assets_attributes
) and multiple
attributes is set to true
.