duyojiぶろぐ

技術系ときどき日常系

S3にAPIからアップロードするとリダイレクトされるときの対処法

失敗時の内容

$credentials = array(
    "key"    => "your_key",
    "secret" => "your_secret"
);

$s3 = new AmazonS3($credentials);

$response = $s3->create_object($bucket, $fileName, array(
    "fileUpload"     => $filePath,
    "acl"                => AmazonS3::ACL_PUBLIC,
    "contentType" => $contentType
));

上記のような感じでアップロードを試みたときうまくいかなかったのでvar_dump($responseで確かめたところ)以下のような出力されて、どうやら正しいエンドポイントをセットしてあげてみたいなことを言われているっぽい。

["body"]=>
  object(CFSimpleXML)#17 (6) {
   ["Code"]=>
    string(17) "PermanentRedirect"
    ["Message"]=>
    string(137) "The bucket you are attempting to access must be addressed using the specified endpoint. Please send all future requests to this endpoint."
    ["RequestId"]=>
    string(16) "xxxxxxxx"
    ["Bucket"]=>
    string(23) "xxx.xxx.xxx.com"
    ["HostId"]=>
    string(64) "xxxxx"
    ["Endpoint"]=>
    string(40) "xxx.xxx.xxx.com.s3.amazonaws.com"
  }
  ["status"]=>
  int(301)

解決方法

以下のように東京リージョンならap-northeast-1なので、以下のようにセットしたらちゃんとアップロードできるようになった。

$s3->set_region(AmazonS3::REGION_APAC_NE1);

参考URL