复制代码
class AmazonAwsBusiness
{
private $key = '';
private $secret = '';
private $region = '';
private $version = 'latest';
private $bucket = 'image';
public function __construct()
{
$this->key = env('AMAZON_AWS.KEY', '');
$this->secret = env('AMAZON_AWS.SECRET', '');
$this->region = env('AMAZON_AWS.REGION', '');
$this->bucket = env('AMAZON_AWS.BUCKET', '');
}
public function createBucketBusiness()
{
$s3 = new S3Client([
'version' => 'latest',
'region' => 'us-2',
// 'endpoint' => 'https://s3.us-west-2.amazonaws.com',
'credentials' => [
'key' => 'YOUR_ACCESS_KEY',
'secret' => 'YOUR_SECRET_KEY',
],
]);
$bucket = 'my-new-bucket';
return $s3->createBucket([
'Bucket' => $bucket,
]);
}
public function listBucketsBusiness()
{
$s3Client = new S3Client([
'region' => $this->region,
'version' => $this->version,
'credentials' => [
'key' => $this->key,
'secret' => $this->secret,
]
]);
return $s3Client->listBuckets();
}
public function uploadImgBusiness($file, $shop_name = '', $type = 1)
{
if ($shop_name == '') {
$shop_name = time();
}
$s3Client = new S3Client([
'region' => $this->region,
'version' => $this->version,
'credentials' => [
'key' => $this->key,
'secret' => $this->secret,
]
]);
if ($type == 1) {
$savename = \think\facade\Filesystem::putFile('wsms3_listings', $file);
$filePath = app()->getRootPath() . '/runtime/storage/' . $savename;
} else {
$filePath = $file;
}
return $s3Client->putObject([
'Bucket' => $this->bucket,
'Key' => $shop_name . '_' . time(),
'SourceFile' => $filePath,
]);
}
/**
* 根据url下载图片 并上传到s3
*/
public function sendUploadImgBusiness($url)
{
$filePath = app()->getRootPath() . '/runtime/storage/wsms3_listings/';
$imgFile = httpTolocal($url, $filePath);
try {
$res = (new AmazonAwsBusiness())->uploadImgBusiness($imgFile, rand(1, 99999), 2);
return $res['ObjectURL'];
} catch (Exception $e) {
return false;
}
}
}