最近做国外项目的时候,需要把文件上传到AWS-S3对象存储空间里,下面整理一下上传方法,和碰到的问题
代码
php
/**
* 亚马逊oss Aws上传
* composer require aws/aws-sdk-php
* @param $filePath
* @param $ossPath
* @return array
* @author wzb
* @data 2024/5/25
*/
function ossAwsUploadFile($filePath = '', $ossPath = '')
{
// 配置信息 composer require aws/aws-sdk-php
$configOss = config('aws_oss');
$accessKeyId = $configOss['accessKeyId'] ?? ''; // 你的AccessKeyId
$accessKeySecret = $configOss['accessKeySecret'] ?? ''; // 你的AccessKeySecret
$endpoint = $configOss['region'] ?? ''; // 你的Bucket所在地域的域名 ap-southeast-1
$bucket = $configOss['bucket'] ?? ''; // 你的Bucket名字
if (empty($accessKeyId) || empty($accessKeySecret) || empty($endpoint) || empty($bucket)) {
return [];
}
$awsConfig = [
'version' => 'latest',//版本
'acl' => 'public-read',//权限//这个一定要加,是访问权限
'bucket' => $bucket,//存储桶名称
'region' => $endpoint,
'key_id' => $accessKeyId,//Access key ID
'access_key' => $accessKeySecret,//Secret access key
];
//实例化
$s3 = new S3Client([
'version' => $awsConfig['version'],//版本
'region' => $awsConfig['region'],//区域
'credentials' => new Credentials(
$awsConfig['key_id'],
$awsConfig['access_key']
),
// 开启bug调试
// 'debug' => true
]);
if (!file_exists($filePath)) {
return [];
}
try {
$result = $s3->putObject([
'Bucket' => $awsConfig['bucket'],
'ACL' => $awsConfig['acl'],//这个一定要加,是访问权限
'Key' => $ossPath, // //亚马逊静态资源服务器上的路径+图片名称
// 'Body' => fopen($filePath, 'r'),
'SourceFile' => $filePath, // 原文件路径
]);
$result = $result->toArray();
$imgUrl = $result['ObjectURL'] ?? '';
return $result;
} catch (Exception $exception) {
echo $exception->getMessage();
return [];
}
}
// 调用示例
$ossInfo = ossAwsUploadFile("F:/wzb/img/5836923c44342.jpg", 'img/5836923c44342.jpg');
碰到的问题
一直报AWS HTTP error: cURL error 60: SSL certificate problem: unable to get local issuer certificate的问题:
下面详细报错信息:
PutObject" on "https://ss.amazonaws.com/img/5836923c44342.jpg"; AWS HTTP error: cURL error 60: SSL certificate problem: unable to get local issuer certificate (see https://curl.haxx.se/libcurl/c/libcurl-errors.html) for https://ss.amazonaws.com/img/5836923c44342.jpg
解决办法
php.ini里面的 curl.cainfo 需要设置
-
下载cacert: https://curl.haxx.se/ca/cacert.pem
-
配置php.ini 并重启
php
curl.cainfo = "真实路径/cacert.pem"