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?
.ajax() function, it is incapable of doing AJAX file uploads.
Remotipart to the rescue! The Remotipart gem does two things:
.ajaxSubmit()function, which uses iFrame technique described in the last article.
remotipart_responseblock 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.
Update: Newer versions have been released since this post. See the Remotipart homepage for the most up-to-date info.
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.
For installation, documentation, and demos, check out the new Remotipart homepage:
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.