Skip to content

Instantly share code, notes, and snippets.

@latortuga
Created December 8, 2012 20:09
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save latortuga/4241707 to your computer and use it in GitHub Desktop.
Save latortuga/4241707 to your computer and use it in GitHub Desktop.
Request Signing for Direct Amazon S3 File Upload
# app/controllers/application_controller.rb
class ApplicationController
private
def generate_s3_upload_data
bucket = BUCKET # S3 bucket
access_key = S3_KEY # S3 Access Key
secret = S3_SECRET # S3 Secret Key
key = "uploadify/" # The folder in your bucket that you'd like uploaded files to land in. See note below.
expiration = 10.hours.from_now.utc.strftime('%Y-%m-%dT%H:%M:%S.000Z')
max_filesize = 100.megabytes
sas = '201' # Tells amazon to redirect after success instead of returning xml
policy = "{'expiration': '#{expiration}',
'conditions': [
{'bucket': '#{bucket}'},
{'acl': 'private'},
{'success_action_status': '#{sas}'},
['starts-with', '$Filename', ''],
['starts-with', '$key', '#{key}'],
['content-length-range', 1, #{max_filesize}]
]}
"
encoded_policy = Base64.encode64(policy).gsub(/\n|\r/, '')
digest = OpenSSL::HMAC.digest(OpenSSL::Digest::Digest.new('sha1'), secret, encoded_policy)
signature = Base64.encode64(digest).gsub(/\n| |\r/, '')
# Return a hash to be used in the view to populate some JS variables.
{
:access_key => access_key,
:key => key,
:policy => encoded_policy,
:signature => signature,
:sas => sas,
:bucket => bucket,
:filesize => max_filesize
}
end
# Call this method in the action with the uploader.
def prepare_uploadify
@uploadify_data = generate_s3_upload_data
@s3_url = "http://s3.amazonaws.com/#{@uploadify_data[:bucket]}"
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment