AmazonS3Service.php
2.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
<?php
/**
* @remark :上传文件与图片到亚马逊
* @name :AmazonS3Service.php
* @author :lyh
* @method :post
* @time :2024/1/23 9:17
*/
namespace App\Services;
use Aws\S3\S3Client;
use Aws\S3\Exception\S3Exception;
class AmazonS3Service
{
// 替换为你自己的 AWS 访问密钥、区域和存储桶名称
protected $s3;
protected $accessKeyId = 'AKIAU6YKND7SAWIKBXCZ';//key
protected $secretAccessKey = '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';//密匙
protected $region = 'us-west-2';//地址
protected $bucket = 'arn:aws:s3:us-west-2:340934860772:accesspoint/globalso-v6';//桶子
public function __construct()
{
// 创建 S3 客户端
$this->s3 = new S3Client([
'version' => 'latest',
'region' => $this->region,
'credentials' => [
'key' => $this->accessKeyId,
'secret' => $this->secretAccessKey,
],
]);
}
/**
* @remark :上传图片与文件
* @name :uploadImage
* @author :lyh
* @method :post
* @time :2024/1/23 9:20
*/
public function uploadFiles(&$files, $s3Key,$filename)
{
$key = ltrim($s3Key.'/'.$filename,'/');
$body = $files->getRealPath();
try {
$result = $this->s3->putObject([
'Bucket' => $this->bucket,
'Key' => $key,
'SourceFile' => $body,
// 'ACL' => 'public-read', // 设置图片为公共可读,可根据需求修改
]);
return $result['ObjectURL'];
} catch (S3Exception $e) {
return false;
}
}
/**
* @remark :同步图片文件到亚马逊
* @name :uploadImage
* @author :lyh
* @method :post
* @time :2024/1/23 9:20
*/
public function syncImageFiles($files)
{
$key = str_replace_url($files);
@file_put_contents(storage_path('logs/lyh_error.log'), var_export($key, true) . PHP_EOL, FILE_APPEND);
$body = $files;
try {
$result = $this->s3->putObject([
'Bucket' => $this->bucket,
'Key' => $key,
'Body' => file_get_contents($body),
]);
@file_put_contents(storage_path('logs/lyh_error.log'), var_export($result, true) . PHP_EOL, FILE_APPEND);
return $result['ObjectURL'];
} catch (AwsException $e) {
@file_put_contents(storage_path('logs/lyh_error.log'), var_export('图片:'.$e->getMessage(), true) . PHP_EOL, FILE_APPEND);
return '上传文件到S3时发生错误:' . $e->getMessage();
}
}
}