HTML Upload to Amazon S3 with Ruby on Rails

This Blog Post will demonstrate how to build a HTML file upload for images with Ruby on Rails and store the images on Amazon S3 Cloud Storage. I assume that you are familiar with Ruby on Rails and RubyGems.

For the connection to Amazons S3 Storage System we will use the gem “aws-s3”. To use this you have to add this line to your Gemfile:

gem 'aws-s3', '0.6.2', :require => 'aws/s3'

After you added the line to your Gemfile, execute:


to load the gem. To use aws-s3 is pretty easy. Just add this lines to your “application.rb” file:

      :access_key_id     => 'your_access_key_id',
      :secret_access_key => 'your_secret_access_key'

Just customize the above lines with your access_key_id and your secret_access_key from your S3 Account. Everytime then you are starting your Ruby App AWS will establish a connection to your S3 storage.

OK. Let’s start with the HTML upload form. Here it is:

 <%= form_for @image, :html => {:multipart => true, :accept => "image/gif,image/png,image/jpg"} do |f| %>

   <div style="width: 400px;" >
     <%= file_field 'upload', 'datafile'  %>

   <%= f.submit "Upload image", :class => "button" %>

<% end  %>

And the corresponding Ruby Controller looks like this:

class ImagesController < ApplicationController

@@BUCKET = "my_image_bucket"

def create
  fileUp = params[:upload]
  orig_filename =  fileUp['datafile'].original_filename
  filename = sanitize_filename(orig_filename), fileUp['datafile'].read, @@BUCKET, :access => :public_read)
  url = AWS::S3::S3Object.url_for(filename, @@BUCKET, :authenticated => false)
  @image =[:image])
  @image.user = current_user
  @image.filename = filename
  @image.url = url;
    flash[:success] = "Image saved! "
    render '/home'
    render '/users/new_image'

def destroy
  AWS::S3::S3Object.find(@image.filename, @@BUCKET).delete
  render '/home'

    def sanitize_filename(file_name)
      just_filename = File.basename(file_name)


That’s it. Just cusotmezice the “@@BUCKET” with your Amazon Bucket name.


The default HTTP libary in Ruby is pretty ugly. I don’t like it. I found HTTParty on rubygems and this is really easy to use. It is much better than the default HTTP API from ruby. Just add this to your Gemfile:

gem 'httparty', '0.7.4'

With one line you can fetch a site via GET.

html_body = HTTParty.get('').response.body

That’s it.