使用cakephp 3

时间:2017-06-27 09:13:40

标签: php cakephp amazon-s3 cakephp-3.0

我正在尝试将文件上传到亚马逊s3。我收到了以下错误

Cannot redeclare GuzzleHttp\uri_template() (previously declared in /var/www/html/appname/vendor/guzzlehttp/guzzle/src/functions‌​.php:17) File /var/www/html/appname/vendor/aws/GuzzleHttp/functions.php 

在上传控制器中,使用以下代码上传

 require_once("../vendor/aws/aws-autoloader.php"); 
 use Aws\S3\S3Client; 

 public function upload(){
   $s3 = S3Client::factory(array(   'version' =>
 'latest',   'region'  => 'ap-south-1',   'credentials' => array(
 'key' => 'key',
 'secret'  => 'secret'   ) ));

    if ($this->request->is('post'))
    {
    if(!empty($this->request->data['file']['name']))
        {
            $fileName = $this->request->data['file']['name'];

                   $s3->putObject([
                        'Bucket'       => backetname,
                        'Key'          => $fileName,
                        'SourceFile'   => $this->request->data['file']['tmp_name'],
                        'ContentType'  => 'image/jpeg',
                        'ACL'          => 'public-read',
                        'StorageClass' => 'REDUCED_REDUNDANCY'
                    ]);
         }                       

      }
}

1 个答案:

答案 0 :(得分:1)

您正在方法之外创建S3客户端的对象,这是方法中$s3null的原因。

您需要在方法本身中创建对象,或者您可以将S3客户端对象存储在类属性中并与$this->s3->putObject()一起使用

最好是创建一个组件,如下所示:

<?php
 namespace App\Controller\Component;
 use Cake\Controller\Component;
 use Aws\S3\S3Client;

 class AmazonComponent extends Component{
    public $config = null;
    public $s3 = null;

    public function initialize(array $config){
        parent::initialize($config);
        $this->config = [
           's3' => [
               'key' => 'YOUR_KEY',
               'secret' => 'YOUR_SECRET',
               'bucket' => 'YOUR_BUCKET',
           ]
        ];
        $this->s3 = S3Client::factory([
            'credentials' => [
               'key' => $this->config['s3']['key'],
               'secret' => $this->config['s3']['secret']
            ],
        'region' => 'eu-central-1',
        'version' => 'latest'
        ]);
    }
}

在控制器中使用此组件。示例如下:

class UploadController extends AppController{
    public $components = ['Amazon'];

    public function upload(){
         $objects = $this->Amazon->s3->putObject([
                        'Bucket'       => backetname,
                        'Key'          => $fileName,
                        'SourceFile'   => $this->request->data['file']['tmp_name'],
                        'ContentType'  => 'image/jpeg',
                        'ACL'          => 'public-read',
                        'StorageClass' => 'REDUCED_REDUNDANCY'
                    ]);
    }
 }