

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

# 객체 관련 작업
<a name="examples-s3-objects"></a>

Amazon S3 객체는 데이터 모음인 *파일*을 나타냅니다. 각 객체는 [버킷](examples-s3-buckets.md) 안에 상주해야 합니다.

## 사전 조건
<a name="codeExamplePrereq"></a>

시작하기 전에 [AWS SDK for C\$1\$1사용 시작하기](getting-started.md)를 읽어보시기 바랍니다.

예제 코드를 다운로드하고 [코드 예제 시작하기](getting-started-code-examples.md)에 설명된 대로 솔루션을 빌드합니다.

예제를 실행하려면 코드에서 요청을 만드는 데 사용하는 사용자 프로필에 AWS (서비스 및 작업에 대한) 적절한 권한이 있어야 합니다. 자세한 내용은 자격 [AWS 증명 제공을](credentials.md) 참조하세요.

## 버킷에 파일 업로드
<a name="upload-object"></a>

`S3Client` 객체의 `PutObject` 함수를 사용하여 버킷 이름, 키 이름 및 업로드할 파일을 제공합니다. `Aws::FStream`은 로컬 파일의 콘텐츠를 버킷에 업로드하는 데 사용됩니다. 버킷이 반드시 있어야 하며, 그렇지 않으면 오류가 발생합니다.

객체를 비동기적으로 업로드하는 예제는 [를 사용한 비동기 프로그래밍 AWS SDK for C\$1\$1](async-methods.md) 섹션을 참조하세요.

 **코드** 

```
bool AwsDoc::S3::putObject(const Aws::String &bucketName,
                           const Aws::String &fileName,
                           const Aws::S3::S3ClientConfiguration &clientConfig) {
    Aws::S3::S3Client s3Client(clientConfig);

    Aws::S3::Model::PutObjectRequest request;
    request.SetBucket(bucketName);
    //We are using the name of the file as the key for the object in the bucket.
    //However, this is just a string and can be set according to your retrieval needs.
    request.SetKey(fileName);

    std::shared_ptr<Aws::IOStream> inputData =
            Aws::MakeShared<Aws::FStream>("SampleAllocationTag",
                                          fileName.c_str(),
                                          std::ios_base::in | std::ios_base::binary);

    if (!*inputData) {
        std::cerr << "Error unable to read file " << fileName << std::endl;
        return false;
    }

    request.SetBody(inputData);

    Aws::S3::Model::PutObjectOutcome outcome =
            s3Client.PutObject(request);

    if (!outcome.IsSuccess()) {
        std::cerr << "Error: putObject: " <<
                  outcome.GetError().GetMessage() << std::endl;
    } else {
        std::cout << "Added object '" << fileName << "' to bucket '"
                  << bucketName << "'.";
    }

    return outcome.IsSuccess();
}
```

[전체 예제](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/s3/put_object.cpp)는 Github에서 확인하세요.

## 버킷에 문자열 업로드
<a name="upload-object-string"></a>

`S3Client` 객체의 `PutObject` 함수를 사용하여 버킷 이름, 키 이름 및 업로드할 파일을 제공합니다. 버킷이 반드시 있어야 하며, 그렇지 않으면 오류가 발생합니다. 이 예제는 `Aws::StringStream`을 사용하여 인 메모리 문자열 데이터 객체를 버킷에 직접 업로드한다는 점에서 이전 예제와 다릅니다.

객체를 비동기적으로 업로드하는 예제는 [를 사용한 비동기 프로그래밍 AWS SDK for C\$1\$1](async-methods.md) 섹션을 참조하세요.

 **코드** 

```
bool AwsDoc::S3::putObjectBuffer(const Aws::String &bucketName,
                                 const Aws::String &objectName,
                                 const std::string &objectContent,
                                 const Aws::S3::S3ClientConfiguration &clientConfig) {
    Aws::S3::S3Client s3Client(clientConfig);

    Aws::S3::Model::PutObjectRequest request;
    request.SetBucket(bucketName);
    request.SetKey(objectName);

    const std::shared_ptr<Aws::IOStream> inputData =
            Aws::MakeShared<Aws::StringStream>("");
    *inputData << objectContent.c_str();

    request.SetBody(inputData);

    Aws::S3::Model::PutObjectOutcome outcome = s3Client.PutObject(request);

    if (!outcome.IsSuccess()) {
        std::cerr << "Error: putObjectBuffer: " <<
                  outcome.GetError().GetMessage() << std::endl;
    } else {
        std::cout << "Success: Object '" << objectName << "' with content '"
                  << objectContent << "' uploaded to bucket '" << bucketName << "'.";
    }

    return outcome.IsSuccess();
}
```

[전체 예제](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/s3/put_object_buffer.cpp)는 Github에서 확인하세요.

## 객체 나열
<a name="list-objects"></a>

버킷 내의 객체 목록을 가져오려면 `S3Client` 객체의 `ListObjects` 함수를 사용합니다. 콘텐츠를 나열할 버킷의 이름이 설정된 `ListObjectsRequest`를 이 함수에 제공합니다.

`ListObjects` 함수는 객체 목록을 `Object` 인스턴스 형태로 가져오는 데 사용할 수 있는 `ListObjectsOutcome` 객체를 반환합니다.

 **코드** 

```
bool AwsDoc::S3::listObjects(const Aws::String &bucketName,
                             Aws::Vector<Aws::String> &keysResult,
                             const Aws::S3::S3ClientConfiguration &clientConfig) {
    Aws::S3::S3Client s3Client(clientConfig);

    Aws::S3::Model::ListObjectsV2Request request;
    request.WithBucket(bucketName);

    Aws::String continuationToken; // Used for pagination.
    Aws::Vector<Aws::S3::Model::Object> allObjects;

    do {
        if (!continuationToken.empty()) {
            request.SetContinuationToken(continuationToken);
        }

        auto outcome = s3Client.ListObjectsV2(request);

        if (!outcome.IsSuccess()) {
            std::cerr << "Error: listObjects: " <<
                      outcome.GetError().GetMessage() << std::endl;
            return false;
        } else {
            Aws::Vector<Aws::S3::Model::Object> objects =
                    outcome.GetResult().GetContents();

            allObjects.insert(allObjects.end(), objects.begin(), objects.end());
            continuationToken = outcome.GetResult().GetNextContinuationToken();
        }
    } while (!continuationToken.empty());

    std::cout << allObjects.size() << " object(s) found:" << std::endl;

    for (const auto &object: allObjects) {
        std::cout << "  " << object.GetKey() << std::endl;
        keysResult.push_back(object.GetKey());
    }

    return true;
}
```

[전체 예제](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/s3/list_objects.cpp)는 Github에서 확인하세요.

## 객체 다운로드
<a name="download-object"></a>

`S3Client` 객체의 `GetObject` 함수를 사용하여 버킷 이름과 다운로드할 객체 키가 설정된 `GetObjectRequest`를 이 함수에 전달합니다. `GetObject`는 [https://docs.aws.amazon.com/sdk-for-cpp/latest/api/aws-cpp-sdk-s3/html/class_aws_1_1_s3_1_1_model_1_1_get_object_result.html](https://docs.aws.amazon.com/sdk-for-cpp/latest/api/aws-cpp-sdk-s3/html/class_aws_1_1_s3_1_1_model_1_1_get_object_result.html) 및 [https://docs.aws.amazon.com/sdk-for-cpp/latest/api/aws-cpp-sdk-s3/html/class_aws_1_1_s3_1_1_s3_error.html](https://docs.aws.amazon.com/sdk-for-cpp/latest/api/aws-cpp-sdk-s3/html/class_aws_1_1_s3_1_1_s3_error.html)로 구성된 [https://docs.aws.amazon.com/sdk-for-cpp/latest/api/aws-cpp-sdk-s3/html/namespace_aws_1_1_s3_1_1_model.html#a6e16a7b25e8c7547934968a538a15272](https://docs.aws.amazon.com/sdk-for-cpp/latest/api/aws-cpp-sdk-s3/html/namespace_aws_1_1_s3_1_1_model.html#a6e16a7b25e8c7547934968a538a15272) 객체를 반환합니다. `GetObjectResult`는 S3 객체의 데이터에 액세스하는 데 사용할 수 있습니다.

다음 예제는 Amazon S3에서 객체를 다운로드합니다. 객체 콘텐츠는 로컬 변수에 저장되고 콘텐츠의 첫 번째 줄이 콘솔에 출력됩니다.

 **코드** 

```
bool AwsDoc::S3::getObject(const Aws::String &objectKey,
                           const Aws::String &fromBucket,
                           const Aws::S3::S3ClientConfiguration &clientConfig) {
    Aws::S3::S3Client client(clientConfig);

    Aws::S3::Model::GetObjectRequest request;
    request.SetBucket(fromBucket);
    request.SetKey(objectKey);

    Aws::S3::Model::GetObjectOutcome outcome =
            client.GetObject(request);

    if (!outcome.IsSuccess()) {
        const Aws::S3::S3Error &err = outcome.GetError();
        std::cerr << "Error: getObject: " <<
                  err.GetExceptionName() << ": " << err.GetMessage() << std::endl;
    } else {
        std::cout << "Successfully retrieved '" << objectKey << "' from '"
                  << fromBucket << "'." << std::endl;
    }

    return outcome.IsSuccess();
}
```

[전체 예제](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/s3/get_object.cpp)는 Github에서 확인하세요.

## 객체 삭제
<a name="delete-object"></a>

`S3Client` 객체의 `DeleteObject` 함수를 사용하여 다운로드할 버킷과 객체의 이름이 설정된 `DeleteObjectRequest`를 이 함수에 전달합니다. *지정된 버킷과 객체 키가 반드시 있어야 하며, 그렇지 않으면 오류가 발생합니다*.

 **코드** 

```
bool AwsDoc::S3::deleteObject(const Aws::String &objectKey,
                              const Aws::String &fromBucket,
                              const Aws::S3::S3ClientConfiguration &clientConfig) {
    Aws::S3::S3Client client(clientConfig);
    Aws::S3::Model::DeleteObjectRequest request;

    request.WithKey(objectKey)
            .WithBucket(fromBucket);

    Aws::S3::Model::DeleteObjectOutcome outcome =
            client.DeleteObject(request);

    if (!outcome.IsSuccess()) {
        auto err = outcome.GetError();
        std::cerr << "Error: deleteObject: " <<
                  err.GetExceptionName() << ": " << err.GetMessage() << std::endl;
    } else {
        std::cout << "Successfully deleted the object." << std::endl;
    }

    return outcome.IsSuccess();
}
```

[전체 예제](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/s3/delete_object.cpp)는 Github에서 확인하세요.