duyojiぶろぐ

技術系ときどき日常系

AWS SDK for PHP2を使ってS3へファイルをアップロード

githubのサンプル(失敗する)

<?php

require 'vendor/autoload.php';

use Aws\Common\Aws;
use Aws\S3\Enum\CannedAcl;
use Aws\S3\Exception\S3Exception;

// Instantiate an S3 client
$s3 = Aws::factory('/path/to/config.php')->get('s3');

// Upload a publicly accessible file. File size, file type, and md5 hash are automatically calculated by the SDK
try {
    $s3->putObject(array(
        'Bucket' => 'my-bucket',
        'Key'    => 'my-object',
        'Body'   => fopen('/path/to/file', 'r'),
        'ACL'    => CannedAcl::PUBLIC_READ
    ));
} catch (S3Exception $e) {
    echo "The file was not uploaded.\n";
}

上のコードを実行すると以下のようにBodyがいけないと怒られる

Fatal error: Uncaught exception 'Guzzle\Service\Exception\ValidationException' with message 'Validation errors: [Body] must be of type string or object' in /usr/local/aws/sdk/php/vendor/guzzle/guzzle/src/Guzzle/Service/Command/AbstractCommand.php:376

ここ
参考に以下のようにコードを書き換える。
注意としては「use Guzzle\Http\EntityBody」を追加している。
(Bodyの指定でEntityBody::factoryを使うようになっているから)

書き換えたコード(成功した)

<?php

require 'vendor/autoload.php';

use Aws\Common\Aws;
use Aws\S3\Enum\CannedAcl;
use Aws\S3\Exception\S3Exception;
use Guzzle\Http\EntityBody;  #追加

// Instantiate an S3 client
$s3 = Aws::factory('/path/to/config.php')->get('s3');

// Upload a publicly accessible file. File size, file type, and md5 hash are automatically calculated by the SDK
try {
    $s3->putObject(array(
        'Bucket' => 'my-bucket',
        'Key'    => 'my-object',
        'Body' => EntityBody::factory(fopen(('/path/to/file', 'r')),
        'ACL'    => CannedAcl::PUBLIC_READ
    ));
} catch (S3Exception $e) {
    echo "The file was not uploaded.\n";
}