113 lines
3.3 KiB
PHP
113 lines
3.3 KiB
PHP
<?php
|
||
// +------------------------------------------------+
|
||
// |http://www.cjango.com |
|
||
// +------------------------------------------------+
|
||
// | 修复BUG不是一朝一夕的事情,等我喝醉了再说吧! |
|
||
// +------------------------------------------------+
|
||
// | Author: 小陈叔叔 <Jason.Chen> |
|
||
// +------------------------------------------------+
|
||
namespace app\common\service;
|
||
|
||
use app\common\model\Storage as StorageModel;
|
||
use think\Config;
|
||
use think\Loader;
|
||
use think\Request;
|
||
use tools\Format;
|
||
|
||
class Storage extends _Init
|
||
{
|
||
|
||
/**
|
||
* 获取存储总量
|
||
* @param array $map
|
||
* @return string
|
||
*/
|
||
public static function total($map = [])
|
||
{
|
||
return Format::byte(StorageModel::where($map)->sum('size'));
|
||
}
|
||
|
||
/**
|
||
* 存储文件所有类型
|
||
* @return array
|
||
*/
|
||
public static function types()
|
||
{
|
||
return StorageModel::field('type')->distinct('type')->select();
|
||
}
|
||
|
||
/**
|
||
* 磁盘剩余空间
|
||
* @return string
|
||
*/
|
||
public static function diskUse()
|
||
{
|
||
$total = disk_total_space(".");
|
||
return round((($total - disk_free_space(".")) / $total) * 100, 2);
|
||
}
|
||
|
||
/**
|
||
* 上传文件
|
||
* @param string $name
|
||
* @return string|array
|
||
*/
|
||
public static function upload($name)
|
||
{
|
||
$File = Request::instance()->file($name);
|
||
// 文件验证
|
||
$validate = Loader::validate('Storage');
|
||
if (!$validate->check([$name => $File])) {
|
||
return $validate->getError();
|
||
}
|
||
|
||
// 检查是否有该文件,如果上传过,直接返回文件信息
|
||
$info = StorageModel::where('hash', $File->hash())->find();
|
||
if ($info) {
|
||
$data = [
|
||
'id' => $info->id,
|
||
'name' => $info->name,
|
||
'path' => ltrim($info->path, '.'),
|
||
];
|
||
return $data;
|
||
}
|
||
|
||
// 保存的规则
|
||
$File->rule(function ($file) {
|
||
$rule = explode('/', $file->getMime())[0] . '/';
|
||
$rule .= date('Y-m/d');
|
||
$rule .= '/' . $file->hash();
|
||
$rule .= '.' . strtolower(pathinfo($file->getInfo('name'), PATHINFO_EXTENSION)); // 文件后缀
|
||
return $rule;
|
||
});
|
||
|
||
$config = Config::get('storage');
|
||
|
||
$fileInfo = $File->move($config['path'], true, $config['replace']);
|
||
|
||
if ($fileInfo) {
|
||
$data = [
|
||
'type' => explode('/', $fileInfo->getMime())[0],
|
||
'name' => rtrim($fileInfo->getInfo('name'), '.' . $fileInfo->getExtension()),
|
||
'ext' => $fileInfo->getExtension(),
|
||
'hash' => $fileInfo->hash(),
|
||
'path' => ltrim($fileInfo->getPathname(), '.'),
|
||
'size' => $fileInfo->getSize(),
|
||
];
|
||
// 保存文件信息
|
||
if ($insert = StorageModel::create($data)) {
|
||
$ret = [
|
||
'id' => $insert->id,
|
||
'name' => $insert->name,
|
||
'path' => ltrim($insert->path, '.'),
|
||
];
|
||
Logs::write('上传文件', $data);
|
||
return $ret;
|
||
} else {
|
||
return '数据保存失败';
|
||
}
|
||
} else {
|
||
return $File->getError();
|
||
}
|
||
}
|
||
}
|