Amazon Simple Storage Service
Developer Guide (API Version 2006-03-01)
« PreviousNext »
View the PDF for this guide.Go to the AWS Discussion Forum for this product.Go to the Kindle Store to download this guide in Kindle format.Did this page help you?  Yes | No |  Tell us about it...

Copy an Object Using the AWS SDK for Ruby

The following tasks guide you through using the Ruby classes to copy an object in Amazon S3, from one bucket to another or to copy an object within the same bucket.

Copying Objects

1

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

2

Execute either the AWS::S3::S3Object#copy_to or AWS::S3::S3Object#copy_from method. You need to provide the request information, such as source bucket name, source key name, destination bucket name, and destination key.


The following Ruby code sample demonstrates the preceding tasks using the #copy_to method to copy an object from one bucket to another.

s3 = AWS::S3.new

# Upload a file and set server-side encryption.
bucket1 = s3.buckets[source_bucket]
bucket2 = s3.buckets[target_bucket]
obj1 = bucket1.objects[source_key]
obj2 = bucket2.objects[target_key]

obj1.copy_to(obj2)

Example

The following Ruby script example makes a copy of an object using the #copy_from method. The copied object with a different key is saved in the same source bucket. For instructions about how to create and test a working sample, see Using the AWS SDK for Ruby.

#!/usr/bin/env ruby

require 'rubygems'
require 'aws-sdk'

bucket_name = '*** Provide bucket name ***'
source_key = '*** Provide source key ***'
target_key = '*** Provide target key ***'

# Get an instance of the S3 interface.
s3 = AWS::S3.new

# Copy the object.
s3.buckets[bucket_name].objects[target_key].copy_from(source_key) 

puts "Copying file #{source_key} to #{target_key}."