以下示例使用 适用于 Java 的 AWS SDK 复制 Amazon S3 中的对象。有关创建和测试有效示例的说明,请参阅《适用于 Java 的 AWS SDK 开发人员指南》中的
入门
。
import com.amazonaws.AmazonServiceException;
import com.amazonaws.SdkClientException;
import com.amazonaws.auth.profile.ProfileCredentialsProvider;
import com.amazonaws.regions.Regions;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.AmazonS3ClientBuilder;
import com.amazonaws.services.s3.model.CopyObjectRequest;
import java.io.IOException;
public class CopyObjectSingleOperation {
public static void main(String[] args) throws IOException {
Regions clientRegion = Regions.DEFAULT_REGION;
String bucketName = "*** Bucket name ***";
String sourceKey = "*** Source object key *** ";
String destinationKey = "*** Destination object key ***";
try {
AmazonS3 s3Client = AmazonS3ClientBuilder.standard()
.withCredentials(new ProfileCredentialsProvider())
.withRegion(clientRegion)
.build();
// Copy the object into a new object in the same bucket.
CopyObjectRequest copyObjRequest = new CopyObjectRequest(bucketName, sourceKey, bucketName, destinationKey);
s3Client.copyObject(copyObjRequest);
} catch (AmazonServiceException e) {
// The call was transmitted successfully, but Amazon S3 couldn't process
// it, so it returned an error response.
e.printStackTrace();
} catch (SdkClientException e) {
// Amazon S3 couldn't be contacted for a response, or the client
// couldn't parse the response from Amazon S3.
e.printStackTrace();
以下 C# 示例使用高级别 适用于 .NET 的 SDK 在单次操作中复制最大为 5 GB 的对象。对于大于 5 GB 的对象,请使用 使用分段上传复制对象 中所述的分段上传复制示例。
此示例将创建最大为 5 GB 的对象的副本。有关设置和运行代码示例的信息,请参阅《适用于 .NET 的 AWS SDK 开发人员指南》中的适用于 .NET 的 AWS SDK 入门。
using Amazon;
using Amazon.S3;
using Amazon.S3.Model;
using System;
using System.Threading.Tasks;
namespace Amazon.DocSamples.S3
class CopyObjectTest
private const string sourceBucket = "*** provide the name of the bucket with source object ***";
private const string destinationBucket = "*** provide the name of the bucket to copy the object to ***";
private const string objectKey = "*** provide the name of object to copy ***";
private const string destObjectKey = "*** provide the destination object key name ***";
// Specify your bucket region (an example region is shown).
private static readonly RegionEndpoint bucketRegion = RegionEndpoint.USWest2;
private static IAmazonS3 s3Client;
public static void Main()
s3Client = new AmazonS3Client(bucketRegion);
Console.WriteLine("Copying an object");
CopyingObjectAsync().Wait();
private static async Task CopyingObjectAsync()
CopyObjectRequest request = new CopyObjectRequest
SourceBucket = sourceBucket,
SourceKey = objectKey,
DestinationBucket = destinationBucket,
DestinationKey = destObjectKey
CopyObjectResponse response = await s3Client.CopyObjectAsync(request);
catch (AmazonS3Exception e)
Console.WriteLine("Error encountered on server. Message:'{0}' when writing an object", e.Message);
catch (Exception e)
Console.WriteLine("Unknown encountered on server. Message:'{0}' when writing an object", e.Message);
此主题将指导您使用第 3 版 适用于 PHP 的 AWS SDK,将 Amazon S3 中的单个对象和多个对象从一个存储桶复制到另一个存储桶或者在同一存储桶中进行复制。
有关适用于 Ruby 的 AWS 开发工具包 API 的更多信息,请转到适用于 Ruby 的 AWS 开发工具包 – 版本 2。
以下 PHP 示例演示使用 copyObject()
方法复制 Amazon S3 中的单个对象。它还演示如何通过使用 getcommand()
方法对 CopyObject
进行批量调用来制作对象的多个副本。
使用 Aws\S3\S3Client
类构造函数创建 Amazon S3 客户端的实例。
$sourceBucket = '*** Your Source Bucket Name ***';
$sourceKeyname = '*** Your Source Object Key ***';
$targetBucket = '*** Your Target Bucket Name ***';
$s3 = new S3Client([
'version' => 'latest',
'region' => 'us-east-1'
// Copy an object.
$s3->copyObject([
'Bucket' => $targetBucket,
'Key' => "$sourceKeyname-copy",
'CopySource' => "$sourceBucket/$sourceKeyname",
// Perform a batch of CopyObject operations.
$batch = array();
for ($i = 1; $i <= 3; $i++) {
$batch[] = $s3->getCommand('CopyObject', [
'Bucket' => $targetBucket,
'Key' => "{targetKeyname}-$i",
'CopySource' => "$sourceBucket/$sourceKeyname",
try {
$results = CommandPool::batch($s3, $batch);
foreach ($results as $result) {
if ($result instanceof ResultInterface) {
// Result handling here
if ($result instanceof AwsException) {
// AwsException handling here
} catch (Exception $e) {
// General error handling here
Python
class ObjectWrapper:
"""Encapsulates S3 object actions."""
def __init__(self, s3_object):
:param s3_object: A Boto3 Object resource. This is a high-level resource in Boto3
that wraps object actions in a class-like structure.
self.object = s3_object
self.key = self.object.key
def copy(self, dest_object):
Copies the object to another bucket.
:param dest_object: The destination object initialized with a bucket and key.
This is a Boto3 Object resource.
dest_object.copy_from(
CopySource={"Bucket": self.object.bucket_name, "Key": self.object.key}
dest_object.wait_until_exists()
logger.info(
"Copied object from %s:%s to %s:%s.",
self.object.bucket_name,
self.object.key,
dest_object.bucket_name,
dest_object.key,
except ClientError:
logger.exception(
"Couldn't copy object from %s/%s to %s/%s.",
self.object.bucket_name,
self.object.key,
dest_object.bucket_name,
dest_object.key,
raise
以下任务将引导您使用 Ruby 类将 Amazon S3 中的对象从一个存储桶复制到另一个存储桶,或者在同一个存储桶内复制。
对 适用于 Ruby 的 AWS SDK 的版本 3 使用 Amazon S3 模块化 Gem 时,需要 aws-sdk-s3
并提供您的 AWS 凭证。有关如何提供凭证的更多信息,请参阅《Amazon S3 API 参考》中的 Making requests using AWS account or IAM user credentials。
attr_reader :source_object
# @param source_object [Aws::S3::Object] An existing Amazon S3 object. This is used as the source object for
# copy actions.
def initialize(source_object)
@source_object = source_object
# Copy the source object to the specified target bucket and rename it with the target key.
# @param target_bucket [Aws::S3::Bucket] An existing Amazon S3 bucket where the object is copied.
# @param target_object_key [String] The key to give the copy of the object.
# @return [Aws::S3::Object, nil] The copied object when successful; otherwise, nil.
def copy_object(target_bucket, target_object_key)
@source_object.copy_to(bucket: target_bucket.name, key: target_object_key)
target_bucket.object(target_object_key)
rescue Aws::Errors::ServiceError => e
puts "Couldn't copy #{@source_object.key} to #{target_object_key}. Here's why: #{e.message}"
# Example usage:
def run_demo
source_bucket_name = "amzn-s3-demo-bucket1"
source_key = "my-source-file.txt"
target_bucket_name = "amzn-s3-demo-bucket2"
target_key = "my-target-file.txt"
source_bucket = Aws::S3::Bucket.new(source_bucket_name)
wrapper = ObjectCopyWrapper.new(source_bucket.object(source_key))
target_bucket = Aws::S3::Bucket.new(target_bucket_name)
target_object = wrapper.copy_object(target_bucket, target_key)
return unless target_object
puts "Copied #{source_key} from #{source_bucket_name} to #{target_object.bucket_name}:#{target_object.key}."
run_demo if $PROGRAM_NAME == __FILE__