built and supported by Alfa Jango


visit alfajango.com » « view all open source projects

Remotipart


AJAX File Uploads in Rails 3

The Remotipart gem enables AJAX file-upload capability to remote forms in Rails 3 apps by extending the native jquery-ujs functionality.

For an introduction explaining how and why Remotipart works, check out AJAX File Uploads with the iFrame Method and Rails 3 AJAX File Uploads with Remotipart.

Dependencies

Installation

Installing is easy. Just add it to your Gemfile:

gem "remotipart", "~> 1.0"

And run:

bundle install

Rails 3.0

For Rails 3.0 apps, run:

bundle exec rails g remotipart:install

This will copy the jquery iframe-transport.js and jquery.remotipart.js files to your public/javascripts directory and add them to your JS :defaults:

<%= javascript_include_tag :defaults %>

Rails 3.1

For Rails 3.1 apps, the required javascript files will be added to the asset pipeline, no installation script necessary. Simply add this to app/assets/javascripts/application.js (make sure to add them just after //= require jquery_ujs):

//= require jquery.remotipart

Now you're ready to start uploading files.

Implementation

Your remote forms are now able to upload files via ajax.

In previous versions, it was required to wrap js.erb responses in a remotipart_response block. This is no longer required in v1.0.

Was the form submitted with Remotipart?

In your controllers, views, or helpers, you may want to know if the form was submitted with Remotipart (using the iframe-transport) or submitted with the native rails jquery-ujs, for whatever reason. Remotipart makes a method available called remotipart_submitted?

if remotipart_submitted?
  # do one thing
else
  # do another
end

Middleware

Remotipart includes a rack middleware that automatically translates the request/response between your app and the iframe-transport when necessary. Because of this, everything just works. no additional configuration needed.

Demo apps and test suite

And that's it! To see it in action, check out the demo Rails app using the remotipart gem for AJAX file uploads in both 3.0 and 3.1 flavors:

The Rails 3.1 demo app also includes a full test suite, using Rspec and Capybara, to test the ajax file uploads. Check out the tests if you're looking for inspiration to write your own.