SDKのインストール
チャネルの登録
#pear channel-discover pear.amazonwebservices.com #pear channel-discover guzzlephp.org/pear #pear channel-discover pear.symfony.com
SDKのインストール
#pear install aws/sdk
WindowsでXAMPP環境の場合もXAMPP Control Panel の Shell を起動して、上記を実行でインストール可能です。
CakePHP2.3のコード
コンポーネント
<?php // SDKの読み込み require 'AWSSDKforPHP/aws.phar'; // 利用クラスの定義 use Aws\Common\Aws; use Aws\Common\Enum\Region; use Aws\S3\Enum\CannedAcl; use Aws\S3\Exception\S3Exception; use Guzzle\Http\EntityBody; class S3FileUploadComponent extends Component { public function upload($tmp,$tmpType,$key){ try { $s3 = Aws::factory(array('key' => 'AccessKey', 'secret' => 'SecretKey', 'region' => Region::AP_NORTHEAST_1))->get('s3'); $response = $s3->putObject(array('Bucket' => 'BucketName', 'Key' => $key, //Directory/FileName 'Body' => EntityBody::factory(fopen($tmp, 'r')), 'ContentType' => $tmpType, 'StorageClass' => 'STANDARD', //'ServerSideEncryption' => 'AES256', 'ACL' => CannedAcl::PUBLIC_READ)); return true; } catch (S3Exception $e) { return false; } } }
コントローラ
public $components = array ('S3FileUpload'); public function add() { if ($this->request->is('post')) { $tmp = $this->request->data['モデル名']['カラム名']['tmp_name']; if(is_uploaded_file($tmp)) { $tmpType = $this->request->data['モデル名']['カラム名']['type']; $p = pathinfo($this->request->data['モデル名']['カラム名']['name']); $fext = $p['extension']; $datetime = date('Ymdhis'); $key = 'files'.'/'.$datetime.'.'.$fext; //S3にファイルアップロード if ($this->S3FileUpload->upload($tmp,$tmpType,$key)){ //成功した時の処理 }else{ //失敗した時の処理 } } } }
ビュー
<?php echo $this->Form->create('モデル名',array('action' => 'add', 'type' => 'file')); ?> <fieldset> <legend><?php echo __('新規登録'); ?></legend> <?php echo $this->Session->flash(); ?> <?php echo $this->Form->input('カラム名',array('label'=>'ラベル名','type'=>'file'));?> <br /> <?php echo $this->Form->button('登録',array('type'=>'submit','class'=>'btn btn-primary'));?> </fieldset> <?php echo $this->Form->end(); ?>