102 lines
3.2 KiB
PHP
102 lines
3.2 KiB
PHP
<?php
|
|
namespace addon\theme_configurator\controller;
|
|
|
|
use app\event\controller\PluginAdminBaseController;
|
|
use think\Response;
|
|
|
|
/**
|
|
* 后台上传控制器
|
|
*
|
|
* 为主题配置插件提供图片上传功能
|
|
*/
|
|
class UploadController extends PluginAdminBaseController
|
|
{
|
|
/**
|
|
* 上传文件
|
|
*
|
|
* @return Response
|
|
*/
|
|
public function upload(): Response
|
|
{
|
|
try {
|
|
// 获取上传的文件
|
|
$file = $this->request->file('file');
|
|
|
|
if (!$file) {
|
|
return json([
|
|
'status' => 400,
|
|
'msg' => lang_plugins('upload_no_file'),
|
|
]);
|
|
}
|
|
|
|
// 验证文件类型和大小
|
|
$fileExt = strtolower($file->extension());
|
|
$fileSize = $file->getSize();
|
|
|
|
$allowedExts = ['jpg', 'jpeg', 'png', 'gif', 'webp', 'svg'];
|
|
$maxSize = 10 * 1024 * 1024; // 10MB
|
|
|
|
if (!in_array($fileExt, $allowedExts)) {
|
|
return json([
|
|
'status' => 400,
|
|
'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',
|
|
]);
|
|
}
|
|
|
|
// 构建保存路径
|
|
$uploadPath = root_path('public') . 'upload' . DIRECTORY_SEPARATOR . 'theme';
|
|
$dateDir = date('Ymd');
|
|
$savePath = $uploadPath . DIRECTORY_SEPARATOR . $dateDir;
|
|
|
|
// 创建目录
|
|
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([
|
|
'status' => 400,
|
|
'msg' => lang_plugins('upload_save_failed'),
|
|
]);
|
|
}
|
|
|
|
// 构建URL路径
|
|
$saveName = 'theme/' . $dateDir . '/' . $fileName;
|
|
$url = '/upload/' . $saveName;
|
|
|
|
return json([
|
|
'status' => 200,
|
|
'msg' => lang_plugins('upload_success'),
|
|
'data' => [
|
|
'save_name' => $saveName,
|
|
'url' => $url,
|
|
'image_url' => $url,
|
|
],
|
|
]);
|
|
|
|
} catch (\Exception $e) {
|
|
return json([
|
|
'status' => 500,
|
|
'msg' => lang_plugins('upload_failed') . ': ' . $e->getMessage(),
|
|
]);
|
|
}
|
|
}
|
|
}
|