Menu
Amazon Simple Storage Service
Developer Guide (API Version 2006-03-01)

Upload an Object Using the AWS SDK for Ruby

The following tasks guide you through using a Ruby script to upload an object for either version of the SDK for Ruby.

Using AWS SDK for Ruby - Version 2

The AWS SDK for Ruby - Version 2 has two ways of uploading an object to Amazon S3. The first is a managed file uploader, which makes it easy to upload files of any size from disk.

Uploading a File

1

Create an instance of the Aws::S3::Resource class.

2

Reference the target object by bucket name and key. Objects live in a bucket and have unique keys that identify the object.

2

Call#upload_file on the object.

Copy
require 'aws-sdk' s3 = Aws::S3::Resource.new(region:'us-west-2') obj = s3.bucket('bucket-name').object('key') obj.upload_file('/path/to/source/file')

The second way that SDK for Ruby - Version 2 can upload an object is to use the #put method of Aws::S3::Object. This is useful if the object is a string or an IO object that is not a file on disk.

Put Object

1

Create an instance of the Aws::S3::Resource class.

2

Reference the target object by bucket name and key.

2

Call#put passing in the string or IO object.

Copy
require 'aws-sdk' s3 = Aws::S3::Resource.new(region:'us-west-2') obj = s3.bucket('bucket-name').object('key') # string data obj.put(body: 'Hello World!') # IO object File.open('source', 'rb') do |file| obj.put(body: file) end

Using AWS SDK for Ruby - Version 1

The API provides a #write method that can take options that you can use to specify how to upload your data.

Uploading Objects - SDK for Ruby - Version 1

1

Create an instance of the AWS::S3 class by providing your AWS credentials.

2

Use the AWS::S3::S3Object#write method which takes a data parameter and options hash which allow you to upload data from a file, or a stream.

The following code sample for the SDK for Ruby - Version 1 demonstrates the preceding tasks and uses the options hash :file to specify the path to the file to upload.

Copy
s3 = AWS::S3.new # Upload a file. key = File.basename(file_name) s3.buckets[bucket_name].objects[key].write(:file => file_name)

Example

The following SDK for Ruby - Version 1 script example uploads a file to an Amazon S3 bucket. For instructions about how to create and test a working sample, see Using the AWS SDK for Ruby - Version 2.

Copy
#!/usr/bin/env ruby require 'rubygems' require 'aws-sdk' bucket_name = '*** Provide bucket name ***' file_name = '*** Provide file name ****' # Get an instance of the S3 interface. s3 = AWS::S3.new # Upload a file. key = File.basename(file_name) s3.buckets[bucket_name].objects[key].write(:file => file_name) puts "Uploading file #{file_name} to bucket #{bucket_name}."