AmazonS3Service.php
3.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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
<?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)
{
$location = '/tmp'.str_replace_url($files);
$file_link = $this->fetchRemoteImage($files,$location);
$key = str_replace_url($files);
try {
$context = stream_context_create([
'ssl' => [
'verify_peer' => false,
'verify_peer_name' => false
]
]);
$file_content = file_get_contents($file_link, false, $context);
$result = $this->s3->putObject([
'Bucket' => $this->bucket,
'Key' => ltrim($key,'/'),
'Body' => $file_content,
]);
unlink($location);
return $result['ObjectURL'];
} catch (AwsException $e) {
return '上传文件到S3时发生错误:' . $e->getMessage();
}
}
/**
* @remark :零时文件
* @name :fetchRemoteImage
* @author :lyh
* @method :post
* @time :2024/1/26 12:48
*/
public function fetchRemoteImage($url, $localPath) {
// 创建 cURL 句柄
$curl = curl_init();
// 设置 cURL 选项
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
// 执行请求并获取内容
$response = curl_exec($curl);
// 检查请求是否成功
if ($response === false) {
$error = curl_error($curl);
// 处理错误
return 'cURL 错误:' . $error;
} else {
// 将内容保存到本地文件
file_put_contents($localPath, $response);
return $localPath;
}
// 关闭 cURL 句柄
curl_close($curl);
}
}