【问题标题】:Handling PostTooLargeException in Laravel 5.5在 Laravel 5.5 中处理 PostTooLargeException
【发布时间】:2018-04-09 18:18:31
【问题描述】:

我正在尝试在我的 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 是空的。 我的重定向有什么问题吗?

谢谢你的帮助!

【问题讨论】:

  • 如果有一些Session 消息,你会检查你的blade 吗?喜欢@if(Session::has('foo') {{ $foo }} @endif
  • @Tarasovych 是的,我有,而且我没有任何会话消息。现在我明白了,在出现PostTooLargeException 的那一刻,会话还没有开始,所以我需要以某种方式开始一个会话......\Session::start()session_start() 没有帮助我,但我没有深入挖掘还是那样……
  • 嗯,很奇怪Session还没开始...

标签: php redirect handler laravel-5.5


【解决方案1】:

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 中,它起作用了。谢谢
猜你喜欢
  • 1970-01-01
  • 2018-09-07
  • 1970-01-01
  • 2019-08-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-07-26
  • 1970-01-01
相关资源
最近更新 更多