Skip to content

Instantly share code, notes, and snippets.

@frankyston
Forked from miligraf/presigned_url.rb
Created October 24, 2023 21:33
Show Gist options
  • Save frankyston/32188d2a64d29dd8094306ff8ed94a9c to your computer and use it in GitHub Desktop.
Save frankyston/32188d2a64d29dd8094306ff8ed94a9c 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>"
@frankyston
Copy link
Author

frankyston commented Oct 24, 2023

require 'aws-sdk-s3'

#credentials below for the IAM user I am using
s3 = Aws::S3::Client.new(
  region:               'us-west-2', #or any other region
  access_key_id:        AWS_ACCESS_KEY_ID,
  secret_access_key:    AWS_SECRET_ACCESS_KEY
)

signer = Aws::S3::Presigner.new(client: s3)
url = signer.presigned_url(
  :put_object,
  bucket: S3_BUCKET_NAME,
  key: "${filename}-#{SecureRandom.uuid}"
)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment