request->file('file'); if (empty($file)) { return json([ 'success' => false, 'message' => '没有接收到文件' ]); } if (is_array($file)) { $file = $file[0]; } $originalName = $file->getInfo('name'); $suffix = strtolower(pathinfo($originalName, PATHINFO_EXTENSION)); $allowedSuffix = ['jpg', 'png', 'gif', 'jpeg', 'webp']; if (!in_array($suffix, $allowedSuffix)) { return json([ 'success' => false, 'message' => '不支持的图片格式' ]); } $fileSize = $file->getSize(); if ($fileSize > 10485760) { return json([ 'success' => false, 'message' => '文件大小超过10MB限制' ]); } $year = date('Y'); $month = date('m'); $day = date('d'); $uploadPath = ROOT_PATH . 'public' . DIRECTORY_SEPARATOR . 'uploads' . DIRECTORY_SEPARATOR . $year . $month . $day . DIRECTORY_SEPARATOR; if (!is_dir($uploadPath)) { mkdir($uploadPath, 0755, true); } $fileName = time() . '.' . $suffix; $info = $file->move($uploadPath, $fileName); if ($info) { $relativePath = 'uploads/' . $year . $month . $day . '/' . $fileName; $fileUrl = $this->request->domain() . '/' . str_replace('\\', '/', $relativePath); return json([ 'success' => true, 'message' => '上传成功', 'data' => [ 'url' => $fileUrl ] ]); } else { return json([ 'success' => false, 'message' => $file->getError() ]); } } /** * 添加产品接口(示例) * POST /api/product/productAdd * * @return \think\response\Json */ public function productAdd() { // 获取请求数据 $data = $this->request->param(); // 验证数据(示例) if (empty($data['code'])) { return json([ 'success' => false, 'message' => '产品编码不能为空' ]); } $res = [ 'product_name' => $data['name'], 'product_code' => $data['code'], 'product_img' => $data['image'], 'createTime' => date('Y-m-d H:i:s'), 'create_name' => '系统摄像头', ]; $res = db('product')->insert($res); if (!$res) { return json([ 'success' => false, 'message' => '添加失败' ]); } return json([ 'success' => true, 'message' => '添加成功', 'data' => $data ]); } } ?>