Rails 3 AJAX File Uploads with Remotipart

12 July 2011

In my last article, we discussed the difficulties of file-uploads via AJAX, and how the iFrame method works around the issues to provide an AJAX-like interface for uploading files to the server.

So how does this relate to Rails?

Rails 3 uses Unobtrusive JavaScript for remote links and forms (and comes packaged with the jquery-ujs driver via the jquery-rails gem as of Rails 3.1!). However, because jquery-ujs relies on jQuery's standard .ajax() function, it is incapable of doing AJAX file uploads.

The Remotipart gem

Remotipart to the rescue! The Remotipart gem does two things:

  1. When non-blank file input fields are detected in a form, remotipart.js hijacks the remote form submission, and instead submits the form using via form.js's .ajaxSubmit() function, which uses iFrame technique described in the last article.
  2. Secondly, Remotipart provides the remotipart_response block method in our response js.erb views. This method first checks to see if the form was hijacked by Remotipart and was thus submitted in an iFrame, and if so, it returns our generated JS inside a textarea element, so that it automatically gets executed in our parent window.

If you're curious about the name, it's a contraction of "remote" and "multipart", as in multipart forms for file uploading. Pronounced remote-ee-part.

Getting started

Update: Newer versions have been released since this post. See the Remotipart homepage for the most up-to-date info.

New release! Remotipart 0.4 for Rails 3.0 and 3.1

I just released Remotipart version 0.4, re-written to work seamlessly with Rails 3 apps. Among other conveniences, this makes installation much simpler. Also, for Rails 3.1 apps, it now works with the built-in asset pipeline.

Check it out

For installation, documentation, and demos, check out the new Remotipart homepage:

A note on extending Rails jQuery UJS

Because we've opened up jquery-ujs's internal functions to be interactive and configurable, it is now easy to augment and build plugins on top of jquery-ujs. Check out the Remotipart source on Github to see this capability in action.

About the author:

Steve Schwartz // Owner of Alfa Jango, CTO of Genomenon, co-founder of Carcode (acquired by Edmunds.com in 2014), engineer, developer, open-source enthusiast, guitarist, and racecar driverist.

Comments are loading...