Last active
December 19, 2015 13:29
-
-
Save STRd6/5962620 to your computer and use it in GitHub Desktop.
Using Amazon S3 as a content addressable store.
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
| <?xml version="1.0" encoding="UTF-8"?> | |
| <CORSConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/"> | |
| <CORSRule> | |
| <AllowedOrigin>*</AllowedOrigin> | |
| <AllowedMethod>GET</AllowedMethod> | |
| <MaxAgeSeconds>3000</MaxAgeSeconds> | |
| <AllowedHeader>Content-*</AllowedHeader> | |
| </CORSRule> | |
| </CORSConfiguration> |
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
| require "digest/sha1" | |
| require "fog" | |
| require "sinatra" | |
| require "tempfile" | |
| configure do | |
| storage = Fog::Storage.new({ | |
| :provider => 'AWS', | |
| :aws_access_key_id => ENV["ACCESS_KEY_ID"], | |
| :aws_secret_access_key => ENV["SECRET_ACCESS_KEY"], | |
| }) | |
| set :bucket, ENV["AWS_BUCKET"] | |
| set :storage, storage | |
| end | |
| post "/upload" do | |
| if data = params[:data] | |
| if data.is_a? String | |
| content_type = params[:type] | |
| file = Tempfile.new ["data", ".json"] | |
| file.write data | |
| file.rewind | |
| else | |
| file = data[:tempfile] | |
| content_type = data[:type] | |
| end | |
| elsif data = params[:data_base64] | |
| content_type = params[:type] | |
| file = Tempfile.new ["image", ".png"], :encoding => 'ascii-8bit' | |
| file.write Base64.decode64(data) | |
| file.rewind | |
| else | |
| return 400 | |
| end | |
| store(file, content_type) | |
| 200 | |
| end | |
| def directory | |
| settings.storage.directories.get(settings.bucket) | |
| end | |
| def store(file, content_type=nil) | |
| sha1 = Digest::SHA1.file(file.path).hexdigest | |
| if directory.files.get(sha1) | |
| # Already stored, do nothing | |
| else | |
| directory.files.create( | |
| :key => sha1, | |
| :body => file, | |
| :content_type => content_type, | |
| :public => true, | |
| :metadata => { | |
| 'Cache-Control' => 'max-age=315576000' | |
| } | |
| ) | |
| end | |
| end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment