Skip to content

Instantly share code, notes, and snippets.

@miligraf
Last active October 24, 2023 21:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save miligraf/4c1a8a951effbc03a188384a24730157 to your computer and use it in GitHub Desktop.
Save miligraf/4c1a8a951effbc03a188384a24730157 to your computer and use it in GitHub Desktop.
Rails - Upload an Object Using a Pre-Signed URL (AWS SDK for Ruby)
Aws.config.update({
region: 'us-east-1',
credentials: Aws::Credentials.new(ENV['AWS_ACCESS_KEY_ID'], ENV['AWS_SECRET_ACCESS_KEY'])
})
S3_BUCKET = Aws::S3::Resource.new.bucket(ENV['S3_BUCKET'])
@post = S3_BUCKET.presigned_post(key: "uploads/#{SecureRandom.uuid}/${filename}", success_action_status: '201', acl: 'public-read')
post = Aws::S3::Resource.new.bucket("fake").presigned_post(key: "uploads/#{SecureRandom.uuid}/${filename}", success_action_status: '201', acl: 'public-read')
#<Aws::S3::PresignedPost:0x007f90c1cadf88 @credentials=#<Aws::Credentials access_key_id="a">, @bucket_region="us-east-1", @bucket_name="fake", @url="https://fake.s3.amazonaws.com", @fields={"key"=>"uploads/f8f0cb43-9b34-4e76-b3e6-c930f1438ec6/${filename}", "success_action_status"=>"201", "acl"=>"public-read"}, @key_set=true, @signature_expiration=2016-12-29 14:04:58 -0500, @conditions=[{"bucket"=>"fake"}, ["starts-with", "$key", "uploads/f8f0cb43-9b34-4e76-b3e6-c930f1438ec6/"], {"success_action_status"=>"201"}, {"acl"=>"public-read"}]>
# POST to @post.url
# send all @post.fields (key => value)
# send image as file (field name)
# Response
# <?xml version="1.0" encoding="UTF-8"?>
# <PostResponse>
# <Location>https://s3.amazonaws.com/S3_BUCKET/uploads/RANDOMLY_GENERATED/image.png</Location>
# <Bucket>S3_BUCKET</Bucket>
# <Key>uploads/RANDOMLY_GENERATED/image.png</Key>
# <ETag>"1234567890asdfghjkl"</ETag>
# </PostResponse>
# "//#{@post.url}/<Key></Key>"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment