php aws_2018-03-06 使用AWS PHP SDK将文件上传到AMAZON S3

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

修改如下内容

e48d82bff20b

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上发现上传图片成功

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值