使用cakephp 3上传AWS S3文件
我正在尝试将文件上传到AmazonS3。我有以下错误使用cakephp 3上传AWS S3文件,php,cakephp,amazon-s3,cakephp-3.0,Php,Cakephp,Amazon S3,Cakephp 3.0,我正在尝试将文件上传到AmazonS3。我有以下错误 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 在上传控制器中,使用下面的代码上传 r
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客户机对象存储在class属性中,并与$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'
]);
}
}
你的HTTP客户端冲突,试试这个插件是的,你是对的,dileep,HTTP客户端冲突。如何解决这个冲突。谢谢,现在就尝试不,这个插件很旧,可能它适用于cakephp 2及以下版本,但我使用的是cakephp 3.4。我已经试过了,但没用。你以前试过那个插件吗?好的,用这个问题添加你的代码。谢谢Dilleep,现在我遇到了这样的错误无法重新声明GuzzleHttp\uri_template()(以前在/var/www/html/appname/vendor/GuzzleHttp/guzzle/src/functions.php:17)文件/var/www/html/appname/vendor/aws/GuzzleHttp/functions.php中声明过,如何解决这个错误看起来你的代码仍然冲突,你没有使用插件吗?是的,我没有使用。。有没有办法解决http冲突?我只是遵循aws文档,在这种情况下,您需要创建aws组件。按照链接创建一个组件。感谢Dileep。我做的和你发布的完全一样,但现在我得到了这个错误:调用未定义的方法GuzzleHttp\Psr7\Uri::composeComponents()File/var/www/html/appname/vendor/aws/GuzzleHttp/Psr7/UriResolver.php行:102
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'
]);
}
}