From 624a2628d0dc69fc1622714895e7673a7bf5abe1 Mon Sep 17 00:00:00 2001 From: "HESU\\HESU" <1696136552@qq.com> Date: Fri, 14 Mar 2025 15:49:54 +0800 Subject: [PATCH] =?UTF-8?q?=E6=96=87=E4=BB=B6=E4=B8=8A=E4=BC=A0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- webman/app/controller/UploadController.php | 98 ++++++++++++++++++++++ webman/config/route.php | 2 + 2 files changed, 100 insertions(+) create mode 100644 webman/app/controller/UploadController.php diff --git a/webman/app/controller/UploadController.php b/webman/app/controller/UploadController.php new file mode 100644 index 0000000..eb2b38e --- /dev/null +++ b/webman/app/controller/UploadController.php @@ -0,0 +1,98 @@ +file('files'); + + // 如果没有文件上传 + if (!$files) { + throw new \Exception('未上传任何文件'); + } + + // 单文件转换为数组统一处理 + if (!is_array($files)) { + $files = [$files]; + } + + $result = []; + foreach ($files as $file) { + // 检查文件是否上传成功 + if (!$file->isValid()) { + throw new \Exception($file->getUploadErrorMessage()); + } + + // 校验文件类型 + if (!in_array($file->getUploadMineType(), $this->allowedMimeTypes)) { + throw new \Exception('不支持的文件类型: ' . $file->getUploadMineType()); + } + + // 校验文件大小 + $fileSize = $file->getSize(); + if ($fileSize > $this->maxFileSize) { + throw new \Exception('文件大小超过限制'); + } + + // 生成唯一文件名(防止覆盖) + $filename = uniqid() . '.' . $file->getUploadExtension(); + + // 保存路径(例如:runtime/uploads/202310) + $savePath = runtime_path('uploads/' . date('Ym/d')); + if (!is_dir($savePath)) { + mkdir($savePath, 0755, true); + } + + // 移动文件到目标路径 + $file->move($savePath . '/' . $filename); + + // 记录上传信息 + Log::info('文件上传成功', [ + 'original_name' => $file->getUploadName(), + 'saved_path' => $savePath . '/' . $filename, + 'size' => $fileSize + ]); + + $result[] = [ + 'original_name' => $file->getUploadName(), + 'saved_name' => $filename, + 'path' => 'uploads/' . date('Ym') . '/' . $filename, + 'size' => $fileSize, + 'mime_type' => $file->getUploadMineType() + ]; + } + + return Util::success($result,'上传成功'); + + } catch (\Throwable $e) { + Log::error('文件上传失败: ' . $e->getMessage()); + + return Util::fail([],$e->getMessage()); + } + } +} \ No newline at end of file diff --git a/webman/config/route.php b/webman/config/route.php index a5064fc..3fafdd5 100644 --- a/webman/config/route.php +++ b/webman/config/route.php @@ -14,6 +14,8 @@ use Webman\Route; +// 文件上传接口 +Route::post('/upload', [app\controller\UploadController::class, 'upload']);