Problem: We have a model(my_image_model), that stores images to our file_system but now we want to start storing images to amazon S3.
Don’t worry, in eight simple steps we can acomplish that. Let’s start!
Solution:
- Download a client to manage amazon’s S3 interface ( I use firefox plugin, S3 organizer)
- Access the S3 account and create a bucket (eg: my_bucket)
- Inside my_bucket, create a folder uploads
- In our environment, install the gem aws-s3 (http://amazon.rubyforge.org/). From the console: gem i aws-s3
- Configure S3 credentials. The file amazon_s3.yml must exists and be in the folder /config of our project
- Modify the model my_image_model.
- If you are in a windows environment you must add the following fix (http://nhw.pl/wp/2008/02/05/why-are-you-doomed-being-ruby-developer-on-windows-platform). Adding this fix is really simple, you have to modify the file ../vendor/plugins/attachment_fu/lib/technoweenie/attachment_fu/backends/s3_backend.rb , the method save_to_storage:
- You are done! You can start uploading files to your S3 bucket!
development:
bucket_name: dev_my_bucket
access_key_id:my_account_access_key_id
secret_access_key: my_account_secret_access_keytest:
bucket_name: test_my_bucket
access_key_id:my_account_access_key_id
secret_access_key: my_account_secret_access_keyproduction:
bucket_name: prod_my_bucket
access_key_id:my_account_access_key_id
secret_access_key: my_account_secret_access_key
has_attachment :storage => :s3,:path_prefix => “/uploads”,:content_type => [ "image/jpg", "image/jpeg",
" image/pjpeg", "image/gif", "image/png"], :max_size => 2.megabyte,
:thumbnails => { :home => ’969×526!’, :page=>’969×480!’, :slideshow=>’534×478!’,
:thumb=>’52×28!’ }validates_as_attachment
def save_to_storage
if save_attachment?
# S3Object.store( full_filename, (temp_path ? File.open(temp_path) : temp_data),
# bucket_name, :content_type => content_type,
# :access => attachment_options[:s3_access] )# FIXME: ugly hack to get it running on windows somehow when You give file handle it won’t read it
if RUBY_PLATFORM =~ /(:?mswin|mingw)/
file_content = “”
if temp_path
file_content = File.open(temp_path, “rb”).read
else
file_content = temp_data
end
S3Object.store(full_filename,file_content,bucket_name,:content_type => content_type,
:access => attachment_options[:s3_access])
else
S3Object.store(full_filename,(temp_path ? File.open(temp_path) : temp_data),
bucket_name, :content_type => content_type, :access => attachment_options[:s3_access])
end
end
@old_filename = nil
trueend