简体   繁体   中英

Recommended way to generate a presigned url to S3 Bucket in Ruby

I am trying to generate a pre-signed url on my Rails server to send to the browser, so that the browser can upload to S3.

It seems like aws-sdk-s3 is the gem to use going forward. But unfortunately, I haven't come across documentation for the gem that would provide clarity. There seem to be a few different ways of doing so, and would appreciate any guidance on the difference in the following methods -

  1. Using Aws::S3::Presigner.new ( https://github.com/aws/aws-sdk-ruby/blob/master/aws-sdk-core/lib/aws-sdk-core/s3/presigner.rb ) but it doesn't seem to take in an object parameter or auth credentials.

  2. Using Aws::S3::Resource.new , but it seems like aws-sdk-resources is not going to be maintained. ( https://aws.amazon.com/blogs/developer/upgrading-from-version-2-to-version-3-of-the-aws-sdk-for-ruby-2/ )

  3. Using Aws::S3::Object.new and then calling the put method on that object.

  4. Using AWS::SigV4 directly.

I am wondering how they differ, and the implications of choosing one over the other? Any recommendations are much appreciated, especially with aws-sdk-s3 .

Thank you!

So, thanks to the tips by @strognjz above, here is what worked for me using `aws-sdk-s3'.

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}"
)

This will work using the aws-sdk-s3 gem

aws_client = 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
)


s3 = Aws::S3::Resource.new(client: aws_client)
bucket = s3.bucket('bucket-name')
obj = bucket.object("${filename}-#{SecureRandom.uuid}")

url = obj.presigned_url(:put)

additional http verbs:

obj.presigned_url(:put)                              
obj.presigned_url(:head)                    
obj.presigned_url(:delete)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM