Skip to content

Instantly share code, notes, and snippets.

@alvinsj
Created August 28, 2013 07:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save alvinsj/6363249 to your computer and use it in GitHub Desktop.
Save alvinsj/6363249 to your computer and use it in GitHub Desktop.
upload and serve file to amazon s3 with sinatra [improved] reference: http://www.millwoodonline.co.uk/blog/upload-to-amazon-s3-with-sinatra
class CreateTableS3Uploads < ActiveRecord::Migration
def up
create_table :s3_uploads do |t|
t. :url
t.timestamps
end
end
def down
drop_table :s3_uploads
end
end
<form action='/upload' method='post' accept-charset="utf-8" enctype="multipart/form-data">
<label for='content_file'>Image</label>
<input type="file" name="content[file]" id="content_file" />
<button type='submit'>Save</button>
</form>
class S3Upload < ActiveRecord::Base
end
def upload(filename, file)
bucket = 'bucket_name'
AWS::S3::Base.establish_connection!(
:access_key_id => ENV['ACCESS_KEY_ID'],
:secret_access_key => ENV['SECRET_ACCESS_KEY']
)
AWS::S3::S3Object.store(
filename,
open(file.path),
bucket
)
policy = AWS::S3::S3Object.acl(filename, bucket)
policy.grants = [ AWS::S3::ACL::Grant.grant(:public_read) ]
AWS::S3::S3Object.acl(filename, bucket, policy)
# return url
return AWS::S3::S3Object.url_for(filename, bucket, :authenticated => false)
end
post '/upload' do
uploaded_url = upload(params[:content]['file'][:filename], params[:content]['file'][:tempfile])
# store the url somewhere
S3Upload.create!(url: uploaded_url)
redirect back
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment