Created
August 28, 2013 07:55
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<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> |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class S3Upload < ActiveRecord::Base | |
end |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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