또는 와 CopyObjectAWS SDK 함께 사용 CLI - AWS SDK 코드 예제

AWS 문서 예제 리포지토리에서 더 많은 SDK GitHub AWS SDK 예제를 사용할 수 있습니다.

기계 번역으로 제공되는 번역입니다. 제공된 번역과 원본 영어의 내용이 상충하는 경우에는 영어 버전이 우선합니다.

또는 와 CopyObjectAWS SDK 함께 사용 CLI

다음 코드 예제는 CopyObject의 사용 방법을 보여 줍니다.

작업 예시는 대규모 프로그램에서 발췌한 코드이며 컨텍스트에 맞춰 실행해야 합니다. 다음 코드 예제에서는 컨텍스트 내에서 이 작업을 확인할 수 있습니다.

.NET
AWS SDK for .NET
참고

에 대한 자세한 내용은 를 참조하세요 GitHub. AWS 코드 예시 리포지토리에서 전체 예시를 찾고 설정 및 실행하는 방법을 배워보세요.

using System; using System.Threading.Tasks; using Amazon.S3; using Amazon.S3.Model; public class CopyObject { public static async Task Main() { // Specify the AWS Region where your buckets are located if it is // different from the AWS Region of the default user. IAmazonS3 s3Client = new AmazonS3Client(); // Remember to change these values to refer to your Amazon S3 objects. string sourceBucketName = "amzn-s3-demo-bucket1"; string destinationBucketName = "amzn-s3-demo-bucket2"; string sourceObjectKey = "testfile.txt"; string destinationObjectKey = "testfilecopy.txt"; Console.WriteLine($"Copying {sourceObjectKey} from {sourceBucketName} to "); Console.WriteLine($"{destinationBucketName} as {destinationObjectKey}"); var response = await CopyingObjectAsync( s3Client, sourceObjectKey, destinationObjectKey, sourceBucketName, destinationBucketName); if (response.HttpStatusCode == System.Net.HttpStatusCode.OK) { Console.WriteLine("\nCopy complete."); } } /// <summary> /// This method calls the AWS SDK for .NET to copy an /// object from one Amazon S3 bucket to another. /// </summary> /// <param name="client">The Amazon S3 client object.</param> /// <param name="sourceKey">The name of the object to be copied.</param> /// <param name="destinationKey">The name under which to save the copy.</param> /// <param name="sourceBucketName">The name of the Amazon S3 bucket /// where the file is located now.</param> /// <param name="destinationBucketName">The name of the Amazon S3 /// bucket where the copy should be saved.</param> /// <returns>Returns a CopyObjectResponse object with the results from /// the async call.</returns> public static async Task<CopyObjectResponse> CopyingObjectAsync( IAmazonS3 client, string sourceKey, string destinationKey, string sourceBucketName, string destinationBucketName) { var response = new CopyObjectResponse(); try { var request = new CopyObjectRequest { SourceBucket = sourceBucketName, SourceKey = sourceKey, DestinationBucket = destinationBucketName, DestinationKey = destinationKey, }; response = await client.CopyObjectAsync(request); } catch (AmazonS3Exception ex) { Console.WriteLine($"Error copying object: '{ex.Message}'"); } return response; } }
  • 자세한 API 내용은 참조CopyObject의 섹션을 참조하세요. AWS SDK for .NET API

Bash
AWS CLI Bash 스크립트 사용
참고

에 대한 자세한 내용은 를 참조하세요 GitHub. AWS 코드 예시 리포지토리에서 전체 예시를 찾고 설정 및 실행하는 방법을 배워보세요.

############################################################################### # function errecho # # This function outputs everything sent to it to STDERR (standard error output). ############################################################################### function errecho() { printf "%s\n" "$*" 1>&2 } ############################################################################### # function copy_item_in_bucket # # This function creates a copy of the specified file in the same bucket. # # Parameters: # $1 - The name of the bucket to copy the file from and to. # $2 - The key of the source file to copy. # $3 - The key of the destination file. # # Returns: # 0 - If successful. # 1 - If it fails. ############################################################################### function copy_item_in_bucket() { local bucket_name=$1 local source_key=$2 local destination_key=$3 local response response=$(aws s3api copy-object \ --bucket "$bucket_name" \ --copy-source "$bucket_name/$source_key" \ --key "$destination_key") # shellcheck disable=SC2181 if [[ $? -ne 0 ]]; then errecho "ERROR: AWS reports s3api copy-object operation failed.\n$response" return 1 fi }
  • 자세한 API 내용은 명령 참조CopyObject의 섹션을 참조하세요. AWS CLI

C++
SDK C++용
참고

에 대한 자세한 내용은 를 참조하세요 GitHub. AWS 코드 예시 리포지토리에서 전체 예시를 찾고 설정 및 실행하는 방법을 배워보세요.

bool AwsDoc::S3::copyObject(const Aws::String &objectKey, const Aws::String &fromBucket, const Aws::String &toBucket, const Aws::S3::S3ClientConfiguration &clientConfig) { Aws::S3::S3Client client(clientConfig); Aws::S3::Model::CopyObjectRequest request; request.WithCopySource(fromBucket + "/" + objectKey) .WithKey(objectKey) .WithBucket(toBucket); Aws::S3::Model::CopyObjectOutcome outcome = client.CopyObject(request); if (!outcome.IsSuccess()) { const Aws::S3::S3Error &err = outcome.GetError(); std::cerr << "Error: copyObject: " << err.GetExceptionName() << ": " << err.GetMessage() << std::endl; } else { std::cout << "Successfully copied " << objectKey << " from " << fromBucket << " to " << toBucket << "." << std::endl; } return outcome.IsSuccess(); }
  • 자세한 API 내용은 참조CopyObject의 섹션을 참조하세요. AWS SDK for C++ API

CLI
AWS CLI

다음 명령은 bucket-1에서 bucket-2로 객체를 복사합니다.

aws s3api copy-object --copy-source bucket-1/test.txt --key test.txt --bucket bucket-2

출력:

{ "CopyObjectResult": { "LastModified": "2015-11-10T01:07:25.000Z", "ETag": "\"589c8b79c230a6ecd5a7e1d040a9a030\"" }, "VersionId": "YdnYvTCVDqRRFA.NFJjy36p0hxifMlkA" }
  • 자세한 API 내용은 명령 참조CopyObject의 섹션을 참조하세요. AWS CLI

Go
SDK Go V2용
참고

에 대한 자세한 내용은 를 참조하세요 GitHub. AWS 코드 예시 리포지토리에서 전체 예시를 찾고 설정 및 실행하는 방법을 배워보세요.

// BucketBasics encapsulates the Amazon Simple Storage Service (Amazon S3) actions // used in the examples. // It contains S3Client, an Amazon S3 service client that is used to perform bucket // and object actions. type BucketBasics struct { S3Client *s3.Client } // CopyToBucket copies an object in a bucket to another bucket. func (basics BucketBasics) CopyToBucket(sourceBucket string, destinationBucket string, objectKey string) error { _, err := basics.S3Client.CopyObject(context.TODO(), &s3.CopyObjectInput{ Bucket: aws.String(destinationBucket), CopySource: aws.String(fmt.Sprintf("%v/%v", sourceBucket, objectKey)), Key: aws.String(objectKey), }) if err != nil { log.Printf("Couldn't copy object from %v:%v to %v:%v. Here's why: %v\n", sourceBucket, objectKey, destinationBucket, objectKey, err) } return err }
  • 자세한 API 내용은 참조CopyObject의 섹션을 참조하세요. AWS SDK for Go API

Java
SDK Java 2.x용
참고

에 대한 자세한 내용은 를 참조하세요 GitHub. AWS 코드 예시 리포지토리에서 전체 예시를 찾고 설정 및 실행하는 방법을 배워보세요.

S3Client를 사용하여 객체를 복사합니다.

/** * Asynchronously copies an object from one S3 bucket to another. * * @param fromBucket the name of the source S3 bucket * @param objectKey the key (name) of the object to be copied * @param toBucket the name of the destination S3 bucket * @return a {@link CompletableFuture} that completes with the copy result as a {@link String} * @throws RuntimeException if the URL could not be encoded or an S3 exception occurred during the copy */ public CompletableFuture<String> copyBucketObjectAsync(String fromBucket, String objectKey, String toBucket) { CopyObjectRequest copyReq = CopyObjectRequest.builder() .sourceBucket(fromBucket) .sourceKey(objectKey) .destinationBucket(toBucket) .destinationKey(objectKey) .build(); CompletableFuture<CopyObjectResponse> response = getAsyncClient().copyObject(copyReq); response.whenComplete((copyRes, ex) -> { if (copyRes != null) { logger.info("The " + objectKey + " was copied to " + toBucket); } else { throw new RuntimeException("An S3 exception occurred during copy", ex); } }); return response.thenApply(CopyObjectResponse::copyObjectResult) .thenApply(Object::toString); }

S3TransferManager를 사용하여 한 버킷에서 다른 버킷으로 객체를 복사합니다. 파일 전체를 보고 테스트합니다.

import org.slf4j.Logger; import org.slf4j.LoggerFactory; import software.amazon.awssdk.core.sync.RequestBody; import software.amazon.awssdk.services.s3.model.CopyObjectRequest; import software.amazon.awssdk.transfer.s3.S3TransferManager; import software.amazon.awssdk.transfer.s3.model.CompletedCopy; import software.amazon.awssdk.transfer.s3.model.Copy; import software.amazon.awssdk.transfer.s3.model.CopyRequest; import java.util.UUID; public String copyObject(S3TransferManager transferManager, String bucketName, String key, String destinationBucket, String destinationKey) { CopyObjectRequest copyObjectRequest = CopyObjectRequest.builder() .sourceBucket(bucketName) .sourceKey(key) .destinationBucket(destinationBucket) .destinationKey(destinationKey) .build(); CopyRequest copyRequest = CopyRequest.builder() .copyObjectRequest(copyObjectRequest) .build(); Copy copy = transferManager.copy(copyRequest); CompletedCopy completedCopy = copy.completionFuture().join(); return completedCopy.response().copyObjectResult().eTag(); }
  • 자세한 API 내용은 참조CopyObject의 섹션을 참조하세요. AWS SDK for Java 2.x API

JavaScript
SDK 용 JavaScript (v3)
참고

에 대한 자세한 내용은 를 참조하세요 GitHub. AWS 코드 예시 리포지토리에서 전체 예시를 찾고 설정 및 실행하는 방법을 배워보세요.

객체를 복사합니다.

import { S3Client, CopyObjectCommand } from "@aws-sdk/client-s3"; const client = new S3Client({}); /** * Copy an Amazon S3 object from one bucket to another. */ export const main = async () => { const command = new CopyObjectCommand({ CopySource: "SOURCE_BUCKET/SOURCE_OBJECT_KEY", Bucket: "DESTINATION_BUCKET", Key: "NEW_OBJECT_KEY", }); try { const response = await client.send(command); console.log(response); } catch (err) { console.error(err); } };
  • 자세한 API 내용은 참조CopyObject의 섹션을 참조하세요. AWS SDK for JavaScript API

Kotlin
SDK Kotlin용
참고

에 대한 자세한 내용은 를 참조하세요 GitHub. AWS 코드 예시 리포지토리에서 전체 예시를 찾고 설정 및 실행하는 방법을 배워보세요.

suspend fun copyBucketObject( fromBucket: String, objectKey: String, toBucket: String, ) { var encodedUrl = "" try { encodedUrl = URLEncoder.encode("$fromBucket/$objectKey", StandardCharsets.UTF_8.toString()) } catch (e: UnsupportedEncodingException) { println("URL could not be encoded: " + e.message) } val request = CopyObjectRequest { copySource = encodedUrl bucket = toBucket key = objectKey } S3Client { region = "us-east-1" }.use { s3 -> s3.copyObject(request) } }
  • API 자세한 내용은 CopyObject의 에서 AWS SDK Kotlin API 참조 를 참조하세요.

PHP
PHP용 SDK
참고

에 대한 자세한 내용은 를 참조하세요 GitHub. AWS 코드 예시 리포지토리에서 전체 예시를 찾고 설정 및 실행하는 방법을 배워보세요.

간단하게 객체를 복사합니다.

$s3client = new Aws\S3\S3Client(['region' => 'us-west-2']); try { $folder = "copied-folder"; $this->s3client->copyObject([ 'Bucket' => $this->bucketName, 'CopySource' => "$this->bucketName/$fileName", 'Key' => "$folder/$fileName-copy", ]); echo "Copied $fileName to $folder/$fileName-copy.\n"; } catch (Exception $exception) { echo "Failed to copy $fileName with error: " . $exception->getMessage(); exit("Please fix error with object copying before continuing."); }
  • 자세한 API 내용은 참조CopyObject의 섹션을 참조하세요. AWS SDK for PHP API

PowerShell
용 도구 PowerShell

예시 1: 이 명령은 “test-files” 버킷의 “sample.txt” 객체를 동일한 버킷으로 복사하지만 새로운 키인 “sample-copy.txt”를 사용합니다.

Copy-S3Object -BucketName amzn-s3-demo-bucket -Key sample.txt -DestinationKey sample-copy.txt

예시 2: 이 명령은 “test-files” 버킷의 “sample.txt” 객체를 "backup-files" 버킷으로 복사하며 “sample-copy.txt” 키를 사용합니다.

Copy-S3Object -BucketName amzn-s3-demo-source-bucket -Key sample.txt -DestinationKey sample-copy.txt -DestinationBucket amzn-s3-demo-destination-bucket

예시 3: 이 명령은 “test-files” 버킷에서 "local-sample.txt"라는 이름의 로컬 파일로 "sample.txt" 객체를 다운로드합니다.

Copy-S3Object -BucketName amzn-s3-demo-bucket -Key sample.txt -LocalFile local-sample.txt

예시 4: 단일 객체를 지정된 파일로 다운로드합니다. 다운로드한 파일은 c:\downloads\data\archive.zip에서 찾을 수 있습니다.

Copy-S3Object -BucketName amzn-s3-demo-bucket -Key data/archive.zip -LocalFolder c:\downloads

예시 5: 지정된 키 접두사와 일치하는 모든 객체를 로컬 폴더로 다운로드합니다. 상대 키 계층 구조는 전체 다운로드 위치에 하위 폴더로 보존됩니다.

Copy-S3Object -BucketName amzn-s3-demo-bucket -KeyPrefix data -LocalFolder c:\downloads
  • API 자세한 내용은 Cmdlet 참조CopyObject의 섹션을 참조하세요. AWS Tools for PowerShell

Python
SDK Python용(Boto3)
참고

에 대한 자세한 내용은 를 참조하세요 GitHub. AWS 코드 예시 리포지토리에서 전체 예시를 찾고 설정 및 실행하는 방법을 배워보세요.

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. """ try: 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
  • API 자세한 내용은 CopyObjectAWS SDK Python(Boto3) API 참조 섹션을 참조하세요.

Ruby
SDK Ruby용
참고

에 대한 자세한 내용은 를 참조하세요 GitHub. AWS 코드 예시 리포지토리에서 전체 예시를 찾고 설정 및 실행하는 방법을 배워보세요.

객체를 복사합니다.

require 'aws-sdk-s3' # Wraps Amazon S3 object actions. class ObjectCopyWrapper 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 end # 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}" end end # Example usage: def run_demo <<<<<<< HEAD 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_name = 'doc-example-bucket1' source_key = 'my-source-file.txt' target_bucket_name = 'doc-example-bucket2' target_key = 'my-target-file.txt' >>>>>>> 999c6133e (fixes) 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}." end run_demo if $PROGRAM_NAME == __FILE__

객체를 복사하고 대상 객체에 서버 측 암호화를 추가합니다.

require 'aws-sdk-s3' # Wraps Amazon S3 object actions. class ObjectCopyEncryptWrapper 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 end # Copy the source object to the specified target bucket, rename it with the target key, and encrypt it. # # @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, encryption) @source_object.copy_to(bucket: target_bucket.name, key: target_object_key, server_side_encryption: encryption) 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}" end end # Example usage: def run_demo <<<<<<< HEAD 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" target_encryption = "AES256" ======= source_bucket_name = 'doc-example-bucket1' source_key = 'my-source-file.txt' target_bucket_name = 'doc-example-bucket2' target_key = 'my-target-file.txt' target_encryption = 'AES256' >>>>>>> 999c6133e (fixes) source_bucket = Aws::S3::Bucket.new(source_bucket_name) wrapper = ObjectCopyEncryptWrapper.new(source_bucket.object(source_key)) target_bucket = Aws::S3::Bucket.new(target_bucket_name) target_object = wrapper.copy_object(target_bucket, target_key, target_encryption) return unless target_object puts "Copied #{source_key} from #{source_bucket_name} to #{target_object.bucket_name}:#{target_object.key} and "\ "encrypted the target with #{target_object.server_side_encryption} encryption." end run_demo if $PROGRAM_NAME == __FILE__
  • 자세한 API 내용은 참조CopyObject의 섹션을 참조하세요. AWS SDK for Ruby API

Rust
SDK Rust용
참고

에 대한 자세한 내용은 를 참조하세요 GitHub. AWS 코드 예시 리포지토리에서 전체 예시를 찾고 설정 및 실행하는 방법을 배워보세요.

/// Copy an object from one bucket to another. pub async fn copy_object( client: &aws_sdk_s3::Client, source_bucket: &str, destination_bucket: &str, source_object: &str, destination_object: &str, ) -> Result<(), S3ExampleError> { let source_key = format!("{source_bucket}/{source_object}"); let response = client .copy_object() .copy_source(&source_key) .bucket(destination_bucket) .key(destination_object) .send() .await?; println!( "Copied from {source_key} to {destination_bucket}/{destination_object} with etag {}", response .copy_object_result .unwrap_or_else(|| aws_sdk_s3::types::CopyObjectResult::builder().build()) .e_tag() .unwrap_or("missing") ); Ok(()) }
  • API 자세한 내용은 Rust 참조 CopyObject의 섹션을 참조하세요. AWS SDK API

SAP ABAP
SDK 에 대한 SAP ABAP
참고

에 대한 자세한 내용은 를 참조하세요 GitHub. AWS 코드 예시 리포지토리에서 전체 예시를 찾고 설정 및 실행하는 방법을 배워보세요.

TRY. lo_s3->copyobject( iv_bucket = iv_dest_bucket iv_key = iv_dest_object iv_copysource = |{ iv_src_bucket }/{ iv_src_object }| ). MESSAGE 'Object copied to another bucket.' TYPE 'I'. CATCH /aws1/cx_s3_nosuchbucket. MESSAGE 'Bucket does not exist.' TYPE 'E'. CATCH /aws1/cx_s3_nosuchkey. MESSAGE 'Object key does not exist.' TYPE 'E'. ENDTRY.
  • API 자세한 내용은 CopyObjectAWS SDK SAP ABAP API 섹션을 참조하세요.

Swift
SDK Swift용
참고

에 대한 자세한 내용은 를 참조하세요 GitHub. AWS 코드 예시 리포지토리에서 전체 예시를 찾고 설정 및 실행하는 방법을 배워보세요.

import AWSS3 public func copyFile(from sourceBucket: String, name: String, to destBucket: String) async throws { let srcUrl = ("\(sourceBucket)/\(name)").addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) let input = CopyObjectInput( bucket: destBucket, copySource: srcUrl, key: name ) do { _ = try await client.copyObject(input: input) } catch { print("ERROR: ", dump(error, name: "Copying an object.")) throw error } }
  • API 자세한 내용은 Swift 참조 CopyObject의 섹션을 참조하세요. AWS SDK API