1、下载aws-sdk-php-laravel
git clone https://github.com/aws/aws-sdk-php-laravel.git
2、安装aws-sdk-php
cd aws-sdk-php-laravel/
curl -sS https://getcomposer.org/installer | php #安装 composer.phar
vim composer.json
修改如下内容
image.png
php composer.phar update
php composer.phar require aws/aws-sdk-php #安装aws-sdk-php
3、在AWS上创建一个存储桶
[root@hostname-172-31-9-249 /data/wwwroot/aws-sdk-php-laravel]# vim create-bucket.php
<?
require 'vendor/autoload.php';
use Aws\S3\S3Client;
$bucketName = 'maiyuan2'; #存储桶的名字
$client = new S3Client([
'version' => 'latest',
'region' => 'us-west-1', #要改为美国西部,不然会报错
'credentials' => [
'key' => '', #访问秘钥
'secret' => '' #私有访问秘钥
]
]);
try {
$result = $client->createBucket([
'Bucket' => $bucketName, // REQUIRED
'ACL' => 'public-read',
]);
} catch (Aws\S3\Exception\S3Exception $e) {
// output error message if fails
echo $e->getMessage();
}
?>
chmod +x create-bucket.php
cd vendor/
chmod +x autoload.php
php create-bucket.php #执行发现在aws上创建存储桶成功
4、上传文件到桶
[root@hostname-172-31-9-249 /data/wwwroot/aws-sdk-php-laravel]# vim upload-to-aws.php
<?
require 'vendor/autoload.php';
use Aws\S3\S3Client;
// Instantiate an Amazon S3 client.
$s3 = new S3Client([
'version' => 'latest',
'region' => 'us-west-1', #改为美国西部
'credentials' => [
'key' => '', #访问秘钥
'secret' => '' #私有访问秘钥
]
]);
$bucketName = 'maiyuan2'; #存储桶的名字
$file_Path = '/data/wwwroot/aws-sdk-php-laravel/QQ图片20180223091800.png'; #要上传的文件的路径
$key = basename($file_Path);
// Upload a publicly accessible file. The file size and type are determined by the SDK.
try {
$result = $s3->putObject([
'Bucket' => $bucketName,
'Key' => $key,
'Body' => fopen($file_Path, 'r'),
'ACL' => 'public-read',
]);
echo $result->get('ObjectURL');
} catch (Aws\S3\Exception\S3Exception $e) {
echo "There was an error uploading the file.\n";
echo $e->getMessage();
}
?>
chmod +x upload-to-aws.php
php upload-to-aws.php #在S3上发现上传图片成功
本文参考:https://github.com/aws/aws-sdk-php-laravel
https://artisansweb.net/upload-files-amazon-s3-using-aws-php-sdk/
https://docs.aws.amazon.com/aws-sdk-php/v3/guide/getting-started/installation.html
网友评论