82 lines
2.7 KiB
PHP
82 lines
2.7 KiB
PHP
<?php
|
|
|
|
namespace app\service;
|
|
|
|
use OSS\OssClient;
|
|
use OSS\Core\OssException;
|
|
|
|
class OssService
|
|
{
|
|
private $accessKeyId;
|
|
private $accessKeySecret;
|
|
private $bucket;
|
|
private $endpoint;
|
|
private $ossClient;
|
|
|
|
public function __construct()
|
|
{
|
|
try {
|
|
$this->accessKeyId = env('OSS_ACCESS_KEY_ID');
|
|
$this->accessKeySecret = env('OSS_ACCESS_KEY_SECRET');
|
|
$this->bucket = env('OSS_BUCKET', 'vehicle-album');
|
|
$this->endpoint = env('OSS_ENDPOINT', 'https://oss-cn-beijing.aliyuncs.com');
|
|
|
|
// 记录配置信息
|
|
error_log("OSS Configuration:");
|
|
error_log("AccessKeyId: " . substr($this->accessKeyId, 0, 4) . "****");
|
|
error_log("Bucket: " . $this->bucket);
|
|
error_log("Endpoint: " . $this->endpoint);
|
|
|
|
$this->ossClient = new OssClient($this->accessKeyId, $this->accessKeySecret, $this->endpoint);
|
|
|
|
// 测试连接
|
|
$this->ossClient->doesBucketExist($this->bucket);
|
|
} catch (OssException $e) {
|
|
error_log("OSS Client Initialization Error: " . $e->getMessage());
|
|
throw new \RuntimeException('OSS Client Initialization Error: ' . $e->getMessage());
|
|
}
|
|
}
|
|
|
|
/**
|
|
* 上传图片到 OSS
|
|
* @param string $filePath 本地文件路径
|
|
* @param string $objectKey OSS上存储的对象名称
|
|
* @return string 图片的 URL
|
|
*/
|
|
public function uploadImage($filePath, $objectKey)
|
|
{
|
|
try {
|
|
// 上传文件到 OSS
|
|
$this->ossClient->uploadFile($this->bucket, $objectKey, $filePath);
|
|
// 构造图片的私有 URL
|
|
$url = $this->generatePrivateUrl($objectKey);
|
|
return $url;
|
|
} catch (OssException $e) {
|
|
// 错误处理
|
|
throw new \RuntimeException('OSS Error: ' . $e->getMessage());
|
|
}
|
|
}
|
|
|
|
/**
|
|
* 生成图片的私有访问 URL
|
|
* @param string $objectKey
|
|
* @return string
|
|
*/
|
|
public function generatePrivateUrl($objectKey, $expireTime = 3600)
|
|
{
|
|
try {
|
|
// 生成 OSS 私有 URL(有效期为 3600 秒)
|
|
$url = $this->ossClient->signUrl($this->bucket, $objectKey, $expireTime);
|
|
// 记录调试信息
|
|
error_log("OSS URL Generation Debug:");
|
|
error_log("Bucket: " . $this->bucket);
|
|
error_log("ObjectKey: " . $objectKey);
|
|
error_log("ExpireTime: " . $expireTime);
|
|
error_log("Generated URL: " . $url);
|
|
return $url;
|
|
} catch (OssException $e) {
|
|
error_log("OSS Error: " . $e->getMessage());
|
|
throw new \RuntimeException('OSS Error: ' . $e->getMessage());
|
|
}
|
|
}
|
|
} |