Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Uploading an image to S3 using aws-sdk v2

Tags:

ruby

aws-sdk

I'm having a hell of a time working with the aws-sdk documentation, all of the links I follow seem outdated and unusable.

I'm looking for a straight forward implementation example of uploading an image file to an S3 bucket in Ruby.

  • let's say the image path is screenshots/image.png
  • and I want to upload it to the bucket my_bucket
  • AWS creds live in my ENV

Any advice is much appreciated.

like image 427
YoDK Avatar asked Feb 17 '15 20:02

YoDK


People also ask

How do I upload images to Amazon S3?

jpg . Sign in to the AWS Management Console and open the Amazon S3 console at https://console.aws.amazon.com/s3/ . In the Buckets list, choose the name of the bucket that you want to upload your folders or files to. Choose Upload.


1 Answers

Here is how you can upload a file from disk to the named bucket and key:

s3 = Aws::S3::Resource.new
s3.bucket('my_bucket').object('key').upload_file('screenshots/image.png')

That is the simplest method. You should replace 'key' with the key you want it stored with in Amazon S3. This will automatically upload large files for you using the multipart upload APIs and will retry failed parts.

If you prefer to upload always using PUT object, you can call #put or use an Aws::S3::Client:

# using put
s3 = Aws::S3::Resource.new
File.open('screenshots/image.png', 'rb') do |file|
  s3.bucket('my_bucket').object('key').put(body:file)
end

# using a client
s3 = Aws::S3::Client.new
File.open('screenshots/image.png', 'rb') do |file|
  s3.put_object(bucket:'my_bucket', key:'key', body:file)
end

Also, the API reference documentation for the v2 SDK is here: http://docs.aws.amazon.com/sdkforruby/api/index.html

like image 77
Trevor Rowe Avatar answered Sep 21 '22 17:09

Trevor Rowe