

翻訳は機械翻訳により提供されています。提供された翻訳内容と英語版の間で齟齬、不一致または矛盾がある場合、英語版が優先します。

# オブジェクトに対するオペレーション
<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)」を参照してください。

 **Code** 

```
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();
}
```

[GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/s3/put_object.cpp) で完全な例をご覧ください。

## バケットに文字列をアップロードする
<a name="upload-object-string"></a>

`S3Client` オブジェクトの `PutObject` 関数の使用時に、バケット名、キー名、アップロードするファイルを指定します。バケットが存在している必要があり、存在しない場合はエラーが発生します。この例では、前回と異なり、`Aws::StringStream` を使用してインメモリの文字列データオブジェクトをバケットに直接アップロードします。

オブジェクトを非同期でアップロードする例については、「[を使用した非同期プログラミング AWS SDK for C\$1\$1](async-methods.md)」を参照してください。

 **Code** 

```
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();
}
```

[GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/s3/put_object_buffer.cpp) で完全な例をご覧ください。

## オブジェクトのリスト化
<a name="list-objects"></a>

バケット内のオブジェクトのリストを取得するには、`S3Client` オブジェクトの `ListObjects` 関数を使用します。リストを取得するバケットの名前を `ListObjectsRequest` で指定して渡します。

`ListObjects` 関数は `ListObjectsOutcome` オブジェクトを返します。このオブジェクトを使用して、`Object` インスタンスの形式でオブジェクトのリストを取得できます。

 **Code** 

```
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;
}
```

[GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/s3/list_objects.cpp) で完全な例をご覧ください。

## オブジェクトのダウンロード
<a name="download-object"></a>

`S3Client` オブジェクトの `GetObject` 関数の使用時に、バケット名とオブジェクトキーを `GetObjectRequest` で指定して渡します。`GetObject` は [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) オブジェクトを返します。このオブジェクトは [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) 構成されています。`GetObjectResult` を使用して、S3 オブジェクトのデータにアクセスできます。

次の例は、Amazon S3 からオブジェクトをダウンロードします。オブジェクトの内容はローカル変数に保存され、最初の 1 行がコンソールに出力されます。

 **Code** 

```
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();
}
```

[GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/s3/get_object.cpp) で完全な例をご覧ください。

## オブジェクトの削除
<a name="delete-object"></a>

`S3Client` オブジェクトの `DeleteObject` 関数の使用時に、ダウンロード対象のバケットとオブジェクトの名前を `DeleteObjectRequest` で指定して渡します。*指定されたバケットとオブジェクトキーが存在している必要があり、存在しない場合エラーが発生します*。

 **Code** 

```
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();
}
```

[GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/s3/delete_object.cpp) で完全な例をご覧ください。