| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889 |
- <?php
- namespace app\common\library;
- use OSS\Core\OssException;
- use OSS\OssClient;
- use think\Config;
- use think\Log;
- /**
- * 阿里云 OSS:上传本地文件,返回可访问 URL(对象建议 public-read,或依赖 Bucket 读策略)。
- */
- class AliyunOss
- {
- /**
- * @param string $localPath 本地文件绝对路径
- * @param string $objectKey OSS 对象键,如 xinhua/2026/05/06/订单号_1.pdf(勿以 / 开头)
- * @return string 成功返回 https 开头完整 URL;失败返回空串
- */
- public static function uploadLocalFile(string $localPath, string $objectKey): string
- {
- $objectKey = ltrim(str_replace('\\', '/', $objectKey), '/');
- if ($objectKey === '' || !is_file($localPath) || !is_readable($localPath)) {
- return '';
- }
- $cfg = Config::get('oss');
- if (!is_array($cfg) || (isset($cfg['enabled']) && $cfg['enabled'] === false)) {
- return '';
- }
- $id = trim((string)($cfg['accessKeyId'] ?? ''));
- $secret = trim((string)($cfg['accessKeySecret'] ?? ''));
- $endpoint = trim((string)($cfg['endpoint'] ?? ''));
- $bucket = trim((string)($cfg['bucket'] ?? ''));
- if ($id === '' || $secret === '' || $endpoint === '' || $bucket === '') {
- return '';
- }
- if (!class_exists(OssClient::class)) {
- Log::write('AliyunOss: OssClient 类不存在,请执行 composer install', 'error');
- return '';
- }
- try {
- $ossClient = new OssClient($id, $secret, $endpoint);
- $ossClient->uploadFile($bucket, $objectKey, $localPath);
- try {
- $ossClient->putObjectAcl($bucket, $objectKey, OssClient::OSS_ACL_TYPE_PUBLIC_READ);
- } catch (\Throwable $e) {
- Log::write('AliyunOss: putObjectAcl 失败(可改 Bucket 策略放行读): ' . $e->getMessage(), 'notice');
- }
- return self::buildPublicUrl($cfg, $objectKey);
- } catch (OssException $e) {
- Log::write('AliyunOss 上传失败: ' . $e->getMessage(), 'error');
- } catch (\Throwable $e) {
- Log::write('AliyunOss 上传异常: ' . $e->getMessage(), 'error');
- }
- return '';
- }
- /**
- * @param array<string, mixed> $cfg
- */
- protected static function buildPublicUrl(array $cfg, string $objectKey): string
- {
- $base = trim((string)($cfg['public_base'] ?? ''));
- if ($base !== '') {
- return rtrim($base, '/') . '/' . $objectKey;
- }
- $host = trim((string)($cfg['host'] ?? ''));
- if ($host === '') {
- $bucket = trim((string)($cfg['bucket'] ?? ''));
- $ep = trim((string)($cfg['endpoint'] ?? ''));
- if ($bucket !== '' && $ep !== '') {
- $host = $bucket . '.' . $ep;
- }
- }
- if ($host === '') {
- return '';
- }
- $host = preg_replace('#^https?://#i', '', $host);
- return 'https://' . $host . '/' . $objectKey;
- }
- }
|