76 lines
2.0 KiB
PHP
76 lines
2.0 KiB
PHP
<?php
|
||
|
||
namespace App\Service\common\upload;
|
||
|
||
use App\BaseApp\BaseNotAuthService;
|
||
use App\Service\common\oss\OssStorageInterface;
|
||
use Illuminate\Support\Facades\Storage;
|
||
|
||
/**
|
||
* 本地磁盘上传;支持 domain / path_prefix 覆盖
|
||
*/
|
||
class LocalhostStorageService extends BaseNotAuthService implements OssStorageInterface
|
||
{
|
||
protected array $config = [
|
||
'domain' => '',
|
||
'path_prefix' => '',
|
||
];
|
||
|
||
/**
|
||
* 注入运行时配置(链式)
|
||
*/
|
||
public function withConfig(array $config): static
|
||
{
|
||
$this->config = array_merge($this->config, $config);
|
||
return $this;
|
||
}
|
||
|
||
public function uploadImage($filePath, string $key): bool|array
|
||
{
|
||
return $this->uploadFile($filePath, $key);
|
||
}
|
||
|
||
public function uploadVideo($filePath, string $key): bool|array
|
||
{
|
||
return $this->uploadFile($filePath, $key);
|
||
}
|
||
|
||
public function deleteImage($key): bool
|
||
{
|
||
return $this->deleteFile($key);
|
||
}
|
||
|
||
public function deleteVideo($key): bool
|
||
{
|
||
return $this->deleteFile($key);
|
||
}
|
||
|
||
/**
|
||
* 写入本地 storage;兼容 UploadedFile 与路径字符串
|
||
*/
|
||
private function uploadFile(mixed $filePath, string $key): bool|array
|
||
{
|
||
$prefix = trim((string) ($this->config['path_prefix'] ?? ''), '/');
|
||
if ($prefix !== '' && !str_starts_with($key, $prefix . '/')) {
|
||
$key = $prefix . '/' . ltrim($key, '/');
|
||
}
|
||
$path = is_object($filePath) && method_exists($filePath, 'getRealPath')
|
||
? $filePath->getRealPath()
|
||
: (string) $filePath;
|
||
if (!Storage::put($key, file_get_contents($path))) {
|
||
return false;
|
||
}
|
||
$domain = rtrim((string) ($this->config['domain'] ?? ''), '/');
|
||
$url = $domain !== '' ? ($domain . '/' . $key) : asset('/storage/' . $key);
|
||
return [
|
||
'key' => $key,
|
||
'url' => $url,
|
||
];
|
||
}
|
||
|
||
private function deleteFile(string $key): bool
|
||
{
|
||
return Storage::delete($key);
|
||
}
|
||
}
|