php对接AWS S3云存储,上传S3及访问权限问题

首先先下载sdk包
https://docs.aws.amazon.com/zh_cn/sdk-for-php/v3/developer-guide/getting-started_installation.html

S3创建存储桶
在这里插入图片描述
去安全凭证-》创建访问秘钥
在这里插入图片描述
创建的时候会提示,主账号创建不安全,这个时候我们需要创建一个IAM账号来创建秘钥
创建的步骤访问这个链接 https://www.codenong.com/a513c91eac7186db59fe/

创建之后来到代码这一块

//$keyName是存储S3的路径
//$filepath是本地图片的路径
awsUploadFile($keyName, $filepath);
//删除本地文件
unlink('.' . $resultData['url']);


function awsUploadFile($keyName, $filepath)
{
	//引入文件
    require_once '../extend/aws/aws-autoloader.php';
    //    set_time_limit(0);
    $awsConfig = [
        'version' => 'latest',//版本
        'acl' => 'public-read',//权限//这个一定要加,是访问权限
        'bucket' => config('site.S3bucket'),//存储桶名称
        'region' => 'ap-southeast-1',//区域 和 亚马逊资源服务器创建的桶块区域一致
        'key_id' => config('site.S3key_id'),//Access key ID
        'access_key' => config('site.S3access_key'),//Secret access key
    ];
    //实例化
    $credentials = new Aws\Credentials\Credentials($awsConfig['key_id'],
        $awsConfig['access_key']);
    $s3 = new Aws\S3\S3Client([
        'version' => $awsConfig['version'],//版本
        'region' => $awsConfig['region'],//区域
        'credentials' => $credentials,
    ]);
    if(!file_exists($filepath)){
        dump('file does not exist');
        exit;
    }
//    $http = new GuzzleHttp\Client();
//    $res = $http->request('GET', $filepath);
    try {
        $result = $s3->putObject([
            'Bucket' => $awsConfig['bucket'],
            'Key' => $keyName,
            'Body' => fopen($filepath, 'r'),
            'ACL' => 'public-read',//这个一定要加,是访问权限
//            'Body' => $res->getBody(),
//            'ContentLength' => $res->getHeader('content-length')[0],
        ]);
    } catch (Exception $exception) {
        echo "Failed to upload $filepath with error: " . $exception->getMessage();
        exit("Please fix error with file upload before continuing.");
    }
    return $result;
}

如果是手动上传的文件需要开一下权限
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值