Last Updated: February 25, 2016
·
1.749K
· djs

A very concise AWS S3 uploader example in Ruby

require "rubygems"
require 'sinatra'
require "aws/s3"

get '/' do
  return %Q{
    <form action="upload" method="post" accept-charset="utf-8" enctype="multipart/form-data">
      <div>
        <input type="file" name="file" value="" id="file">
      </div>
      <div>
        <input type="submit" value="Upload &uarr;">
      </div>
    </form>
  }
end

post '/upload' do
  awskey     = 'mykey'
  awssecret  = 'mysecret'
  bucket     = 'mybucket'
  file       = params[:file][:tempfile]
  filename   = params[:file][:filename]
  AWS::S3::Base.establish_connection!(
    :access_key_id     => awskey,
    :secret_access_key => awssecret
  )
  AWS::S3::S3Object.store(
    filename,
    open(file.path),
    bucket,
    :access => :public_read
  )
  url = "https://#{bucket}.s3.amazonaws.com/#{filename}"
  return url
end