首先先下载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/
创建之后来到代码这一块
php
//$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;
}
如果是手动上传的文件需要开一下权限