The attachment_fu plugin written by technoweenie takes care of uploading and retrieving files using S3 and CloudFront, it has other options too such has saving to the database, local file system, rack space. Anyways in this post I describe how to use the plugin with S3 and CloudFront
- Create a sample rails project.
- Install aws-s3 gem, ‘sudo gem install aws-s3‘.
- Install attachment_fu plugin “./script/plugin install git://github.com/technoweenie/attachment_fu.git“.
- Assuming that you already have an Amazon S3 account, create a new S3 bucket.
- Next step is to sign up for the Amazon CloudFront, this is Amazon’s CDN and like any other AWS you pay for what you use, in addition it integrates with your S3 buckets.
- Now log into the CloudFront’s console and create a new distribution channel that is backed with the S3 bucket created in above steps.
- Rename amazon_s3.yml.tpl to amazon_s3.yml (it will be in your config folder)
- Edit the amazon_s3.yml file and fill in the appropriate information.
- Make a model ‘./script/generate model file_meta_data size:integer content_type:string filename:string’ .
- Edit the newly created model and add the following lines to it.( ‘has_attachment’ and ‘validated_as_attachment’ are provided by the plugin, there are many other options that you can specify to read more on the options refer to this page).
- Generate controller ‘./script/generate controller Upload index show new edit create update destroy’.
- Edit the Upload controller and add the following
- Edit the new.erb.html file under the upload controller folder and add the following
- Edit the index.html.erb file under the Uploads controller and add the following
- Edit the Routes and add this new route “map.upload_file ‘/new’, :controller => ‘upload’, :action => ‘create’“
- Run migrations
- And run the server, that’s it now you browse to http://localhost:3000/upload/new to upload a file.
has_attachment :storage => :s3, :cloudfront => true validates_as_attachment
def index @fileMetaDatas = FileMetaData.all end def new @fileMetaData = FileMetaData.new end def create @fileMetaData = FileMetaData.new(params[:fileMetaData]) if @fileMetaData.save flash[:notice] = 'File was successfully created.' redirect_to :controller => :upload, :action => :index else render :action => :new end end
<form_for(:fileMetaData, :url => upload_file_path, :html => { :multipart => true }) do |f| > Upload A File: <%= f.file_field :uploaded_data %> <%= submit_tag 'Create' %> <% end -%>
File List <% for fileMetaData in @fileMetaDatas -%> <%= link_to fileMetaData.public_filename,fileMetaData.public_filename %> <% end %>