在Laravel 5.5中处理PostTooLargeException

4

我正在尝试处理我的Laravel 5.5应用程序中的PostTooLargeException

当我尝试通过表单上传过大的文件时,我会收到PostTooLargeException,我成功地在app\Exceptions\Handler.php中捕获它,但在此步骤上,我想将用户重定向回带有表单的页面并显示错误消息。

我编写了以下代码:

class Handler extends ExceptionHandler
{
...
    public function render($request, Exception $exception)
    {
    ...
        if($exception instanceof PostTooLargeException){
                    return redirect()->back()->withErrors("Size of attached file should be less ".ini_get("upload_max_filesize")."B", 'addNote');
            }
    ...
    }
}

作为结果,我被重定向到正确的页面,但没有任何消息,ViewErrorBag为空。我的重定向有什么问题吗?
感谢您的帮助!

你是否在 blade 模板中检查是否存在一些 Session 消息?例如 @if(Session::has('foo') {{ $foo }} @endif - Tarasovych
@Tarasovych 是的,我检查过了,并没有任何会话消息。现在我明白了,当出现PostTooLargeException异常时,会话尚未开始,所以我需要想办法启动会话...\Session::start()session_start()都没有帮助我,但我还没有深入研究这个方向... - lubart
很奇怪,Session 没有启动... - Tarasovych
1个回答

4
ViewErrorBag为空,因为在Handler中未启动会话。先前,解决方案由@TalinonLaracast中描述。
为了使会话在Handler类中可用,我将\Illuminate\Foundation\Http\Middleware\ValidatePostSize::class$middleware移到$middlewareGroups数组中的App/Http/Kernel.php
我的更新后的$middlewareGroups数组如下:
protected $middlewareGroups = [
        'web' => [
            \App\Http\Middleware\EncryptCookies::class,
            \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
            \Illuminate\Session\Middleware\StartSession::class,
            \Illuminate\Foundation\Http\Middleware\ValidatePostSize::class, // <<< this line was added
            \Illuminate\View\Middleware\ShareErrorsFromSession::class,
            \App\Http\Middleware\VerifyCsrfToken::class,
            \Illuminate\Routing\Middleware\SubstituteBindings::class,

        ],
        ...
];

看起来它工作了,但是出现了一个错误 PHP Warning: POST Content-Length of 8978294 bytes exceeds the limit of 8388608 bytes in Unknown on line 0。根据您的答案,我将 \Illuminate\Session\Middleware\StartSession::class 添加到 $middleware 中,然后它就可以工作了。谢谢。 - simpsons3

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接