Handle File Uploads Easily in Rails
Recently I have been working with file uploads quote a bit in Ruby on Rails. In the past I have struggled through the process of allowing a user to upload a file (whether it be an image or a PDF file) from a web form. Let’s just say that this represents one of those occasions that I am glad to be using Ruby on Rails, due mainly to a nice little plugin called “attachment_fu” by Rick Olson. This is a file upload plugin that makes the process of uploading files from web forms almost trivial, and makes the uploading, resizing, and thumbnailing of uploaded images much, much easier.
Installation is as simple as typing:
script/plugin install http://svn.techno-weenie.net/projects/plugins/attachment_fu/
in the root directory of your Rails application. This will download the plugin from the repository and install it in your Rails application. One thing to remember is that it requires an image processor to be installed on the machine you are working with, and the web server that will be hosting your application. You can choose from ImageScience, RMagick or minimagick, and there is plenty of documentation out there to get these installed. Once you have the plugin installed, and the image processor installed, you are ready to upload files to your Rails applications.
For the most part, this plugin makes files uploads simple. You can easily set the type of file, such as PNG or PDF, that you want to allow to be uploaded. You can even validate file uploads based on the file size. Files can be stored on the filesystem, as binary data in a database, or on Amazon’s S3 storage service. Uploaded images can be resized easily based on an aspect ratio, and creating additional thumbnail images of smaller sizes is so simple it is mind-boggling. Needless to say that integrating file uploads into your forms is also made simple and elegant.
I’m not going to go into a tutorial on how to use the plugin, since the README file for attachment_fu is pretty comprehensive. However, I wanted to reflect as a developer on what a help plugins like this are. Rather than dealing with the technical aspects of how to securely upload images and other files, I can concentrate on how I want my application to work. My time is spent working out usability issues and interface ideas, which is a good thing.
Thanks to folks like Rick Olsen, I have a tool that let’s me concentrate on what is important, so keep an eye out for plugins that you might be able to develop to benefit others.