Files

89 lines
2.4 KiB
PHP

<?php
// +----------------------------------------------------------------------
// | YwxApp [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2026-2036 http://ywxapp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Author: ywxapp<admin@ywxapp.cn>
// +----------------------------------------------------------------------
namespace ywxapp\utils\storage;
use OSS\OssClient;
use OSS\Core\OssException;
use think\file\UploadedFile;
/**
* AliOssStorage 类
*
* @author ywxapp <admin@ywxapp.cn>
*/
class AliOssStorage implements StorageInterface
{
protected $config;
protected $ossClient;
public function __construct(array $config)
{
$this->config = $config;
$this->ossClient = new OssClient(
$config['access_key_id'],
$config['access_key_secret'],
$config['endpoint']
);
}
public function upload(UploadedFile $file, string $path, array $options = []): array
{
try {
$this->ossClient->uploadFile(
$this->config['bucket'],
$path,
$file->getRealPath()
);
return [
'url' => $this->getUrl($path),
'path' => $path,
'storage' => 'alioss'
];
} catch (OssException $e) {
throw new \Exception('阿里云上传失败: ' . $e->getMessage());
}
}
public function delete(string $path): bool
{
try {
$this->ossClient->deleteObject($this->config['bucket'], $path);
return true;
} catch (\Exception $e) {
return false;
}
}
public function getUrl(string $path): string
{
// 如果配置了CDN域名,优先使用
if (!empty($this->config['cdn_domain'])) {
return rtrim($this->config['cdn_domain'], '/') . '/' . ltrim($path, '/');
}
// 否则使用OSS默认域名
return "https://{$this->config['bucket']}.{$this->config['endpoint']}/{$path}";
}
public function exists(string $path): bool
{
try {
$this->ossClient->getObjectMeta($this->config['bucket'], $path);
return true;
} catch (\Exception $e) {
return false;
}
}
}