thinkphp 图片上传验证

时间:2024-03-12 20:44:12

thinkphp中已经有对图片上传做了很好的验证 使用如下:

验证器类中写:

namespace app\index\validate;

use think\Validate;

class User extends Validate
{
    protected $rule = [
        \'test\' => [\'require\', \'image\' => \'225,225\', \'fileExt\' => \'png,jpg\', \'fileSize\' => 6500],
    ];

    protected $message = [
        \'test.image\' => \'不是225,225的图形\',
        \'test.fileExt\' => \'图片的格式不符合要求\',
        \'test.fileSize\' => \'内容不能大于6500字节\',
    ];

    protected $scene = [
        \'edit\' => [\'test\'](这里是场景)
    ];

控制器中验证:

public function trr(Request $request)
    {
        //获取上传文件
        $file = $request->file(\'image\');
        //先验证是否满足条件
        $result = $this->validate([\'test\' => $file], \'User.edit\');
        if (true === $result) {
            //满足条件再做业务逻辑
            $info = $file->move(ROOT_PATH.\'public\'.DS.\'uploads\');
        } else {
            dump($result);
        }
    }