我正在尝试将文件上传到亚马逊 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'
]);
}
}
}
要创建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'
]);
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句