57 lines
1.6 KiB
PHP
57 lines
1.6 KiB
PHP
<?php
|
|
namespace app\chat\controller;
|
|
|
|
use support\Request;
|
|
use support\Response;
|
|
use support\File;
|
|
|
|
class UploadController
|
|
{
|
|
/**
|
|
* 图片上传(相册/拍照)
|
|
*/
|
|
public function image(Request $request): Response
|
|
{
|
|
$file = $request->file('image');
|
|
if (!$file || !$file->isValid()) {
|
|
return json(['code' => 400, 'msg' => '图片上传失败']);
|
|
}
|
|
|
|
// 校验配置
|
|
$uploadConfig = config('process')['chat-gateway']['options']['upload'] ?? [];
|
|
$maxSize = $uploadConfig['image_size'] ?? 5 * 1024 * 1024;
|
|
$allowTypes = $uploadConfig['image_type'] ?? ['image/jpeg', 'image/png', 'image/gif'];
|
|
|
|
// 校验类型和大小
|
|
if (!in_array($file->getMimeType(), $allowTypes)) {
|
|
return json(['code' => 400, 'msg' => '仅支持JPG、PNG、GIF格式']);
|
|
}
|
|
if ($file->getSize() > $maxSize) {
|
|
return json(['code' => 400, 'msg' => "图片大小不能超过" . ($maxSize / 1024 / 1024) . "MB"]);
|
|
}
|
|
|
|
// 保存路径
|
|
$saveDir = public_path() . '/uploads/images/' . date('Ymd');
|
|
if (!is_dir($saveDir)) {
|
|
mkdir($saveDir, 0755, true);
|
|
}
|
|
|
|
// 生成文件名
|
|
$ext = $file->getExtension();
|
|
$filename = uniqid() . '.' . $ext;
|
|
$savePath = $saveDir . '/' . $filename;
|
|
|
|
// 移动文件
|
|
$file->moveTo($savePath);
|
|
|
|
// 访问URL
|
|
$imageUrl = '/uploads/images/' . date('Ymd') . '/' . $filename;
|
|
|
|
return json([
|
|
'code' => 200,
|
|
'msg' => '上传成功',
|
|
'data' => ['image_url' => $imageUrl]
|
|
]);
|
|
}
|
|
}
|