Laravel-AWS S3控制台+API完整流程

735次阅读
没有评论

控制台设置
1.创建桶

2.开启权限

3.编辑储存桶策略

4.策略生成器

点击生成JSON策略
可参考:https://www.bilibili.com/video/BV1yg4y1i79v?t=887

5.访问图片
1.此时已经对该桶设置公有访问,上传的所有文件都可以通过url访问

API 文件上传/删除
1.安装扩展
composer require aws/aws-sdk-php-laravel

2.注册服务

app/config/app.php

// 将下面代码追加到 providers 数组中
Aws\Laravel\AwsServiceProvider::class,

// 将下面代码追加到 aliases 数组中
‘AWS’ => Aws\Laravel\AwsFacade::class,

3.配置文件

app/config/aws.php

return [
‘version’ =>’latest’,
‘region’ => env(‘AWS_REGION’, ‘ap-south-1’),
‘endpoint’ => env(‘AWS_ENDPOINT’, ‘https://sharerabc.s3.ap-south-1.amazonaws.com’),
‘use_path_style_endpoint’ =>true,
‘credentials’ => [
‘key’ => env(‘AWS_KEY’, ‘YOUR_AWS_ACCESS_KEY’),
‘secret’ => env(‘AWS_SECRET’, ‘YOUR_AWS_SECRET_KEY’),
],
‘Ses’ => [
‘region’ => env(‘AWS_SES_REGION’, ‘ap-south-1’),
],
];

4.服务器上传证书

/home/www/.aws/

vim credentials(文件名必须:credentials)

[default]
aws_access_key_id = YOUR_AWS_ACCESS_KEY
aws_secret_access_key = YOUR_AWS_SECRET_KEY

[project1]
aws_access_key_id = YOUR_AWS_ACCESS_KEY
aws_secret_access_key = YOUR_AWS_SECRET_KEY

5.文件上传
public function add(){
$s3Client = AwsFacade::createClient(‘s3’);

    $s3_return = $s3Client->putObject([
        'Bucket' => date('Ymd'), //存储桶(我的理解就是文件系统中的目录)
        'Key' => time() . '.png', //文件名(包括后缀名)
        'Body' => file_get_contents('img/demo.png') //要上传的文件
    ]);

    if($s3_return['@metadata']['statusCode'] == 200){
        echo $s3_return['@metadata']['effectiveUri'];
    } else {
        echo '返回值错误 : return fail! ';
    }
}

6.文件删除
public function del(){
$s3Client = AwsFacade::createClient(‘s3’);
$bucket = ‘demo’;

    $s3Client->deleteObjects([
        'Bucket'  => $bucket,
        'Delete' => [
            'Objects' => [['Key' => '20210208/1612777025.png']]
        ]
    ]);
}

7.遍历桶文件
public function list(){
$s3 = new S3Client([
‘version’ => ‘latest’,
‘region’ => ‘ap-south-1’
]);

    $bucket = 'demo';

    $keys = $s3->listObjects([
        'Bucket' => $bucket
    ]);

    foreach ($keys['Contents'] as $key) {
        echo $key['Key'].'<br>';
    }
}

输出

正文完
可以使用微信扫码关注公众号(ID:xzluomor)
post-qrcode
 
评论(没有评论)