Skip to content

Instantly share code, notes, and snippets.

@dansimco
Created May 29, 2012 15:09
Show Gist options
  • Star 15 You must be signed in to star a gist
  • Fork 4 You must be signed in to fork a gist
  • Save dansimco/2828955 to your computer and use it in GitHub Desktop.
Save dansimco/2828955 to your computer and use it in GitHub Desktop.
Concise Sinatra Amazon S3 Upload Example
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
@dansimco
Copy link
Author

NB: Don't leave your aws key and secret in the committed ruby file, use an external config file (or heroku's config system) to keep sensitive stuff like this out of your repo.

@cyrildiagne
Copy link

Thanks, exactly what I needed!
For some reason this code does not work with EU based S3 buckets. Had to create an US Standard to get it to work!

@nfriend21
Copy link

works like a charm!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment