多应用+插件架构,代码干净,二开方便,首家独创一键云编译技术,文档视频完善,免费商用码云13.8K 广告
>[danger] 传入验证规则数组 ``` // img 是文件字段域名 $file = request()->file('img'); try { // 使用验证器验证上传的文件 validate( [ 'file' => [ // 限制文件大小(单位b),这里限制为4M 'fileSize' => 4 * 1024 * 1024, // 限制文件后缀,多个后缀以英文逗号分割 'fileExt' => 'gif,jpg' ] ], [ 'file.fileSize' => '文件太大', 'file.fileExt' => '不支持的文件后缀', ] )->check(['file' => $file]); // 上传到本地服务器 // ................. $savename = \think\facade\Filesystem::disk('public')->putFile('img', $file); $path = \think\Facade\Filesystem::getDiskConfig('public', 'url') . str_replace('\\', '/', $savename); } catch (\think\exception\ValidateException $e) { return $e->getMessage(); } ``` >[danger] 传入验证器类名 + 验证器类如果还有其他字段的验证 + 则可以指定验证场景使其只进行文件上传验证 ``` <?php namespace app\validate; use think\Validate; class User extends Validate { /** * 定义验证规则 * 格式:'字段名' => ['规则1','规则2'...] * * @var array */ protected $rule = [ 'username' => 'require', 'password' => 'require', 'file' => [ // 限制文件大小(单位b),这里限制为4M 'fileSize' => 4 * 1024 * 1024, // 限制文件后缀,多个后缀以英文逗号分割 'fileExt' => 'gif' ] ]; /** * 定义错误信息 * 格式:'字段名.规则名' => '错误信息' * * @var array */ protected $message = [ 'username.require' => '用户名不能为空', 'password.require' => '登录密码不能为空', 'file.fileSize' => '文件太大', 'file.fileExt' => '不支持的文件后缀', ]; /** * 文件上传 */ public function sceneAvatar() { return $this->only(['file']); } } ``` ``` // pic 文件字段域名称 $file = request()->file('pic'); try { validate('app\validate\User') ->scene('avatar') ->check(['file' => $file]); } catch (\think\exception\ValidateException $e) { dump('文件上传验证失败: ' . $e->getMessage()); } ```