87 lines
3.1 KiB
PHP
87 lines
3.1 KiB
PHP
<?php
|
|
|
|
namespace app\common\service;
|
|
|
|
use support\exception\BusinessException;
|
|
use support\Log;
|
|
use support\Request;
|
|
|
|
class UploadService
|
|
{
|
|
|
|
/**
|
|
* 从服务器本地路径上传文件到 OSS
|
|
*
|
|
* @param Request $request
|
|
* - path: 本地文件绝对路径
|
|
* - scene: 业务分区/场景(可选)
|
|
* - category: 文件分类(可选)
|
|
* - original_name: 原始文件名(可选)
|
|
*/
|
|
public function uploadLocalFile($param)
|
|
{
|
|
try {
|
|
$filePath = $param['path'];
|
|
$scene = $param['scene'];
|
|
$category = $param['category']??'general';
|
|
$providedOriginalName = $param['original_name'];
|
|
|
|
if (empty($filePath)) {
|
|
Log::error('本地文件路径不能为空',$param);
|
|
throw new BusinessException('本地文件路径不能为空');
|
|
}
|
|
|
|
if (!file_exists($filePath) || !is_readable($filePath)) {
|
|
Log::error('本地文件不存在或不可读',$param);
|
|
throw new BusinessException('本地文件不存在或不可读');
|
|
}
|
|
if (empty($scene)) {
|
|
Log::error('上传场景不能为空',$param);
|
|
throw new BusinessException('上传场景不能为空');
|
|
}
|
|
|
|
$basename = basename($filePath);
|
|
$originalName = $providedOriginalName ?: $basename;
|
|
$extensionFromName = pathinfo($originalName, PATHINFO_EXTENSION);
|
|
$extensionFromPath = pathinfo($basename, PATHINFO_EXTENSION);
|
|
$extension = $extensionFromName ?: $extensionFromPath;
|
|
|
|
$mime = mime_content_type($filePath) ?: 'application/octet-stream';
|
|
$size = filesize($filePath) ?: 0;
|
|
|
|
$sceneUrl = $scene ? ($scene . '/') : '';
|
|
$dir = 'x_server/' . $sceneUrl . date('Ymd') . '/';
|
|
$uniqueName = md5($originalName . microtime(true));
|
|
$objectKey = $dir . $uniqueName . ($extension ? ('.' . $extension) : '');
|
|
|
|
$ossService = new OssService();
|
|
$ossService->uploadImage($filePath, $objectKey);
|
|
$privateUrl = $ossService->generatePrivateUrl($objectKey);
|
|
|
|
// 记录文件信息到数据库
|
|
$uploadedFilesService = new UploadedFilesService();
|
|
$fileInfo = [
|
|
'file_name' => $objectKey,
|
|
'file_path' => $objectKey,
|
|
'file_size' => $size,
|
|
'file_type' => $mime,
|
|
'original_name' => $originalName,
|
|
];
|
|
$recordResult = $uploadedFilesService->recordFileInfo($fileInfo, null, $scene, $category);
|
|
|
|
$data = [
|
|
'original_name' => $originalName,
|
|
'file_name' => $objectKey,
|
|
'file_url' => $privateUrl,
|
|
'file_id' => $recordResult['id'] ?? null,
|
|
'partition' => $scene,
|
|
'category' => $category,
|
|
];
|
|
|
|
return $data;
|
|
} catch (\Throwable $e) {
|
|
Log::error($e->getMessage(),$param);
|
|
throw new BusinessException($e->getMessage());
|
|
}
|
|
}
|
|
} |