上传接口
All checks were successful
continuous-integration/drone/push Build is passing

This commit is contained in:
yiqiu
2025-12-28 13:03:48 +08:00
parent a9864b0cd0
commit 82e1ee9ad2

View File

@@ -3,7 +3,6 @@ namespace addon\theme_configurator\controller;
use app\event\controller\PluginAdminBaseController; use app\event\controller\PluginAdminBaseController;
use think\Response; use think\Response;
use think\facade\Filesystem;
/** /**
* 后台上传控制器 * 后台上传控制器
@@ -30,33 +29,57 @@ class UploadController extends PluginAdminBaseController
]); ]);
} }
// 验证文件 // 验证文件类型和大小
$validate = [ $fileExt = strtolower($file->extension());
'size' => 10 * 1024 * 1024, // 10MB $fileSize = $file->getSize();
'ext' => 'jpg,jpeg,png,gif,webp,svg',
]; $allowedExts = ['jpg', 'jpeg', 'png', 'gif', 'webp', 'svg'];
$maxSize = 10 * 1024 * 1024; // 10MB
try {
validate($validate)->check(['file' => $file]); if (!in_array($fileExt, $allowedExts)) {
} catch (\Exception $e) {
return json([ return json([
'status' => 400, 'status' => 400,
'msg' => lang_plugins('upload_validate_failed') . ': ' . $e->getMessage(), 'msg' => lang_plugins('upload_validate_failed') . ': ' . '仅支持 jpg, jpeg, png, gif, webp, svg 格式',
]);
}
if ($fileSize > $maxSize) {
return json([
'status' => 400,
'msg' => lang_plugins('upload_validate_failed') . ': ' . '文件大小不能超过 10MB',
]); ]);
} }
// 上传到本地服务器 // 构建保存路径
$saveName = Filesystem::disk('public')->putFile('theme', $file); $uploadPath = root_path('public') . 'upload' . DIRECTORY_SEPARATOR . 'theme';
$dateDir = date('Ymd');
$savePath = $uploadPath . DIRECTORY_SEPARATOR . $dateDir;
if (!$saveName) { // 创建目录
if (!is_dir($savePath)) {
if (!mkdir($savePath, 0755, true)) {
return json([
'status' => 400,
'msg' => lang_plugins('upload_save_failed') . ': 无法创建上传目录',
]);
}
}
// 生成唯一文件名
$fileName = md5(uniqid() . microtime()) . '.' . $fileExt;
$fullPath = $savePath . DIRECTORY_SEPARATOR . $fileName;
// 移动文件
if (!$file->move($savePath, $fileName)) {
return json([ return json([
'status' => 400, 'status' => 400,
'msg' => lang_plugins('upload_save_failed'), 'msg' => lang_plugins('upload_save_failed'),
]); ]);
} }
// 构建完整的URL路径 // 构建URL路径
$url = '/upload/' . str_replace('\\', '/', $saveName); $saveName = 'theme/' . $dateDir . '/' . $fileName;
$url = '/upload/' . $saveName;
return json([ return json([
'status' => 200, 'status' => 200,