Laravel 5.5中PostTooLargeException的捕获与重定向处理
解决Laravel 5.5中PostTooLargeException的重定向与错误提示问题
嘿,我来帮你搞定这个文件上传过大的异常处理问题!你已经成功在Handler.php里捕获到了PostTooLargeException,接下来只要添上重定向回表单并显示错误提示的逻辑就行,直接看完整的代码实现:
首先,确保你的Handler类顶部引入了对应的异常类,然后在render方法里补充处理逻辑:
use Illuminate\Http\Exceptions\PostTooLargeException; class Handler extends ExceptionHandler { // ... 你已有的其他代码(比如$dontReport数组等) public function render($request, Exception $exception) { // 专门处理文件上传过大的异常 if ($exception instanceof PostTooLargeException) { // 自定义你想展示给用户的错误提示 $errorMsg = "上传文件体积超出限制啦!请上传小于" . ini_get('upload_max_filesize') . "的文件"; // 重定向回表单页面,并把错误信息存入session return redirect()->back()->withErrors(['upload_error' => $errorMsg]); } // 保留框架默认的其他异常处理逻辑 return parent::render($request, $exception); } }
接下来,在你的表单页面(对应的Blade模板)里,添加错误信息的展示代码,这样用户就能看到提示了:
<!-- 放在表单上方合适的位置 --> @if($errors->has('upload_error')) <div class="alert alert-danger"> {{ $errors->first('upload_error') }} </div> @endif
额外小提示
PostTooLargeException本质是PHP配置限制导致的,如果你想允许更大的文件上传,记得修改服务器上的php.ini配置:
upload_max_filesize = 20M # 单个文件最大上传体积 post_max_size = 20M # POST请求的总最大体积(要大于等于upload_max_filesize)
修改后记得重启你的Web服务器(比如Nginx、Apache)让配置生效。
内容的提问来源于stack exchange,提问作者lubart
相关产品推荐
相关产品推荐

