19
votes

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.

1
when I follow those examples I get errors like: undefined method `write' for #<Aws::S3::Object bucket_name="my_bucket", key="image.png"> (NoMethodError)YoDK
I ended up using this answer (stackoverflow.com/questions/130948/ruby-convert-file-to-string) then used object = bucket.object('image.png') object.put(body: contents)YoDK
@EldadMor You linked to the v1 documentation. The v2 documentation is found here: docs.aws.amazon.com/sdkforruby/api/index.htmlTrevor Rowe

1 Answers

36
votes

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