83 lines
2.5 KiB
PHP
83 lines
2.5 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 think\file\UploadedFile;
|
|
|
|
/**
|
|
* LocalStorage 类
|
|
*
|
|
* @author ywxapp <admin@ywxapp.cn>
|
|
*/
|
|
class LocalStorage implements StorageInterface
|
|
{
|
|
protected $config;
|
|
|
|
|
|
public function __construct(array $config)
|
|
{
|
|
$this->config = $config;
|
|
}
|
|
|
|
/**
|
|
* 解析存储根目录(支持绝对路径与相对 public 目录的相对路径)
|
|
*/
|
|
protected function getRoot(): string
|
|
{
|
|
$root = $this->config['root'] ?? 'storage';
|
|
// 绝对路径(Windows 盘符 或 Unix 根目录)直接使用,不再拼接 public_path
|
|
if (preg_match('#^[a-zA-Z]:[\\\\/]|^/#', $root)) {
|
|
return rtrim($root, '/\\');
|
|
}
|
|
return rtrim(public_path() . ltrim($root, '/\\'), '/\\');
|
|
}
|
|
|
|
|
|
public function upload(UploadedFile $file, string $path, array $options = []): array
|
|
{
|
|
// 移动文件到指定目录
|
|
$root = $this->getRoot();
|
|
$url = $this->config['url'] ?? '/storage';
|
|
|
|
$dir = $root . DIRECTORY_SEPARATOR . ltrim($path, '/\\');
|
|
if (! is_dir($dir)) {
|
|
mkdir($dir, 0777, true);
|
|
}
|
|
|
|
$ext = $file->extension() ?: pathinfo($file->getOriginalName(), PATHINFO_EXTENSION);
|
|
$savename = date('His') . '_' . uniqid() . '.' . $ext;
|
|
$file->move($dir, $savename);
|
|
|
|
$realName = $file->getSaveName() ?: $savename;
|
|
$relative = ltrim($path, '/\\') . '/' . $realName;
|
|
return [$realName, $relative, rtrim($url, '/') . '/' . $relative];
|
|
}
|
|
|
|
|
|
public function delete(string $path): bool
|
|
{
|
|
$fullPath = $this->getRoot() . DIRECTORY_SEPARATOR . ltrim($path, '/\\');
|
|
return file_exists($fullPath) && unlink($fullPath);
|
|
}
|
|
|
|
|
|
public function getUrl(string $path): string
|
|
{
|
|
$domain = $this->config['domain'] ?? '';
|
|
return rtrim($domain, '/') . '/' . ltrim($path, '/');
|
|
}
|
|
|
|
|
|
public function exists(string $path): bool
|
|
{
|
|
$fullPath = $this->getRoot() . DIRECTORY_SEPARATOR . ltrim($path, '/\\');
|
|
return file_exists($fullPath);
|
|
}
|
|
}
|