Adam Stacoviak changelog.com/posts

Remotipart - Rails 3 AJAX file uploads made easy

I’ll be honest: I hate uploading files. It shouldn’t be hard, but it always is, because there are so many details. The core case is so simple: You just need an <input> with the file type. Then you forget to make your form multipart, or configure your webserver to not time out for large files, or you want a progress indicator…

The last one is always AJAX. AJAX, AJAX, AJAX. If you’ve had to write this yourself, you know that you end up doing silly stuff with iframe injection, and it always feels so sloppy. Well, that’s why remotipart exists. It doesn’t get rid of the base issue (we’ll leave that up to the standards people), but it does make it super, ultra, mega easy to turn your regular upload form into an AJAX one.

Three steps: install the gem, add :remote => true to your form options, and wrap your response with a remotipart_response block. Here’s the full example, from the README:

sample_layout.html.erb

<%= form_for @sample, :html => { :multipart => true }, :remote => true do |f| %>
  <div class="field">
    <%= f.label :file %>
    <%= f.file_field :file %>
  </div>
  <div class="actions">
    <%= f.submit %>
  </div>
<% end %>

sample_controller.rb

def create
  respond_to do |format|
    if @sample.save
      format.js
    end
  end
end

create.js.erb

<%= remotipart_response do %>
  // Display a Javascript alert
  alert('success!');
  <% if remotipart_submitted? %>
    alert('submitted via remotipart')
  <% else %>
    alert('submitted via native jquery-ujs')
  <% end %>
<% end %>

That simple. Bam. I love Rails 3’s unobtrusive Javascript.


Discussion

Sign in or Join to comment or subscribe

Player art
  0:00 / 0:00