:attachment_fu and Amazon’s S3 For File Uploading
posted by sean on July 30th, 2007
Most of the Rails sites I have been developing lately have been using a plugin called attachment_fu by Rick Olson - one of the core developers of Rails. attachment_fu is easily and effortless - allowing me to add the ability to add "attachments" or uploads to any model within my application. After reading the excellent tutorial by Mike Clark, I was up and running in no time.
class Download < ActiveRecord::Base
has_attachment :storage => :file_system,
:path_prefix => "/public/downloads/",
:max_size => 30.megabytes
end
And in my view(s):
<td class="input_field"> < %= f.file_field :uploaded_data %> </td>
But after a while, downloads started to build up in size consumed, and backups were using valuable bandwidth (since backups moved the files off the server). I remember reading on the excellent tutorial by Mike Clark how easy it looked to change the storage to use Amazon's Simple Storage Service (S3). I installed the AWS::S3 Ruby library, and even played around with s3sh - the interactive shell utility that comes with the AWS::S3 library.
Revisiting the tutorial, I changed my Download model to:
class Download < ActiveRecord::Base
has_attachment :storage => :s3, :max_size => 30.megabytes
end
And created my config/amazon_s3.yml configuration file:
production: bucket_name: my_bucket access_key_id: XXXXXX secret_access_key: XXXXXX
After a few quick tests, everything was working perfectly. Now the only problem I had was moving the existing downloads into the S3 account. I figured the best way to go was to integrate a rake task to help me out.
desc "Move all downloads to Amazon's S3"
task :move_to_s3 => [:environment] do |e|
require 'rubygems'
require 'aws/s3'
AWS::S3::Base.establish_connection!(
:access_key_id => 'XXXXXX',
:secret_access_key => 'XXXXXXX'
)
Download.find(:all).each do |d|
AWS::S3::S3Object.store("/path_on_s3/to_new/download",
open("/path/to/where/current/file/is_located"),
'my_bucket',
:access => :public_read)
end
end
All done. Total cost to move all this stuff over to S3 was about $.10 .
Also, if you're interested, check out S3Fox - a plugin for Mozilla Firefox that allows you to browse, organize, and store your files into your S3 account - all through Firefox.



1 comment »
Very nice howto.
thanks a lot…