2017-06-27 177 views
1

我想實現文件上傳到亞馬遜s3。我發現了以下錯誤AWS S3文件上傳使用cakephp 3

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' 
        ]); 
     }      

     } 
} 
+0

你的HTTP客戶端是相互矛盾的,試試這個插件https://github.com/mikesmullin/CakePHP-AWS-S3-Plugin –

+0

是啊你是對的迪利普,HTTP客戶端是相互矛盾的。如何解決這個衝突。 – Ashok

+0

謝謝,現在試試 – Ashok

回答

1

你正在創建這是原因,在$s3方法是該方法的外部S3客戶端的一個目的null

要麼你需要的方法來創建對象本身,也可以存儲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' 
        ]); 
    } 
} 
+0

感謝Dilleep,現在我收到了一些像這樣的錯誤'不能重新聲明GuzzleHttp \ uri_template()(以前在/var/www/html/appname/vendor/guzzlehttp/guzzle/src/functions.php:17中聲明) File/var/www/html/appname/vendor/aws/GuzzleHttp/functions.php',如何解決這個錯誤 – Ashok

+0

好像你的代碼仍然有衝突,你沒有使用插件? –

+0

是的,我沒有使用..有什麼辦法來解決這個http衝突?我只是遵循aws doc – Ashok