在使用 ThinkPHP6 的 validate 验证器进行文件上传验证时,可以通过 try...catch 语句捕捉到验证器抛出的异常信息,然后根据不同的异常类型进行相应的提示。

比如,当文件大小超过限制时,validate 会抛出 \think\exception\ValidateException 异常,我们可以在 catch 块中通过判断异常类型来进行提示,例如:

try {
    validate(['file' => [
        // 限制文件大小(单位 b),这里限制为 4M
        'fileSize' => json_decode($site_config['web_upload_config'], true)['site_upload_filesize'] * 1024 * 1024,
        // 限制文件后缀,多个后缀以英文逗号分割
        'fileExt'  => json_decode($site_config['web_upload_config'], true)['site_upload_filetext']
    ]])->check(['file' => $file]);
} catch (\think\exception\ValidateException $e) {
    // 文件大小超过限制的异常处理
    if ($e->getError() === 'file.fileSize') {
        $maxSize = json_decode($site_config['web_upload_config'], true)['site_upload_filesize'];
        $errorMsg = '文件大小不能超过' . $maxSize . 'M';
    }
    // 文件类型不合法的异常处理
    else if ($e->getError() === 'file.fileExt') {
        $allowedExt = json_decode($site_config['web_upload_config'], true)['site_upload_filetext'];
        $errorMsg = '文件类型不合法,只允许上传' . $allowedExt . '格式的文件';
    }
    // 其他异常处理
    else {
        $errorMsg = '文件上传失败,请重试';
    }
    // 在页面中输出错误提示
    echo "<script>alert('$errorMsg');</script>";
}

更多规则请看‘上传验证’的规则,文档地址 https://www.kancloud.cn/manual/thinkphp6_0/1037629#_444

ThinkPHP6 文件上传验证:超过限制大小如何提示

原文地址: https://www.cveoy.top/t/topic/oGTa 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录