ThinkChat2.0新版上线,更智能更精彩,支持会话、画图、阅读、搜索等,送10W Token,即刻开启你的AI之旅 广告
> 在File.php中对上传方法进行独立封装 ``` /** * 上传单个文件 * @param Request $request Request实例 * @param string $field 表单字段名称 * @param string $category 文件分类,user或enterprise * @param integer $id user_id或enterprise_id * @param array $rule 文件验证规则,可以对大小,文件类型和后缀名进行验证:['size'=>15678,'ext'=>'jpg,png,gif'] * @return array|false 在上传成功后将返回文件信息,失败时返回false */ public function upload($request, $field = 'file', $category = 'user', $id = 0, $rule = []) { $file = $request->file($field); if (empty($file)) { $this->setError(1, '文件上传错误'); return false; } $basePath = $request->env('ROOT_PATH') . 'public'; $baseUrl = DIRECTORY_SEPARATOR . implode(DIRECTORY_SEPARATOR, ['upload', $category, $id]) . DIRECTORY_SEPARATOR; // 定义路径,upload为子目录 $path = $basePath . $baseUrl; $result = $file->validate($rule)->move($path);//THINKPHP框架的上传方法 if ($result) { return [ 'name' => $result->getInfo('name'), 'file' => $result->getFileName(), 'type' => $result->getInfo('type'), 'size' => $result->getInfo('size'), 'url' => $baseUrl . $result->getSaveName(), 'path' => $path . $result->getSaveName(), ]; } $this->setError(2, $file->getError()); return false; } ``` > 控制器调用File.php中的upload方法 ``` public function update(Request $request, $id) { $data = $request->put(); $file = $request->file('avatar');//获取表单上传文件 $company = new Companys; if (!empty($file)) { $company_id = $id; $FileUpload = File::upload($request, 'avatar', 'company', $company_id, ['ext' => 'jpg,jpeg,png,gif,bmp']); if (!$FileUpload) { $this->error(File::error()->message); } $data['avatar'] = $FileUpload['url']; $enterpriseUser = $this->enterprise_user['id']; $uploadResult = $company->edit($data, $company_id, $enterpriseUser);//调用model层的更新方法 if (!$uploadResult) { $this->error('上传头像失败'); } $this->redirect(url('user/company/read', ['id' => $company_id])); } ```