Files
code-bang/backend/application/common/service/OssService.php
T
2026-09-17 16:25:31 +08:00

85 lines
2.2 KiB
PHP

<?php
namespace app\common\service;
use app\common\traits\ServiceTrait;
use OSS\OssClient;
use OSS\Core\OssException;
use think\Exception;
class OssService
{
use ServiceTrait;
protected $ossClient;
protected $bucket;
protected $domain;
public function __construct()
{
$config = config('common.oss');
try {
$this->ossClient = new OssClient(
$config['access_key_id'],
$config['access_key_secret'],
$config['endpoint']
);
$this->bucket = $config['bucket'];
$this->domain = $config['domain'];
} catch (OssException $e) {
throw new Exception('OSS初始化失败:' . $e->getMessage());
}
}
/**
* 上传文件
* @param string $filePath 本地文件路径
* @param string $object OSS存储路径
* @return string 文件访问URL
* @throws Exception
*/
public function uploadFile($filePath, $object)
{
try {
$result = $this->ossClient->uploadFile($this->bucket, $object, $filePath);
if (!$result) {
throw new Exception('文件上传失败');
}
return $result['oss-request-url'];
} catch (OssException $e) {
throw new Exception('文件上传失败:' . $e->getMessage());
}
}
/**
* 删除文件
* @param string $object OSS存储路径
* @return bool
* @throws Exception
*/
public function deleteFile($object)
{
try {
$this->ossClient->deleteObject($this->bucket, $object);
return true;
} catch (OssException $e) {
throw new Exception('文件删除失败:' . $e->getMessage());
}
}
/**
* 获取文件临时访问URL
* @param string $object OSS存储路径
* @param int $timeout 超时时间(秒)
* @return string
* @throws Exception
*/
public function getSignedUrl($object, $timeout = 3600)
{
try {
return $this->ossClient->signUrl($this->bucket, $object, $timeout);
} catch (OssException $e) {
throw new Exception('获取文件访问地址失败:' . $e->getMessage());
}
}
}