【问题标题】:Laravel 5.5 - Handling PostTooLargeException for large base64 image?Laravel 5.5 - 处理大型 base64 图像的 PostTooLargeException?
【发布时间】:2017-09-20 15:53:40
【问题描述】:

我对每个图像的接受限制为 10MB,任何更大的内容都会阻止代码的执行。我不知道该怎么做。这是我尝试过的:

在控制器方法中:

// Increase memory limit before processing
ini_set('memory_limit','256M');

$base64_image = $request->get('base64_image');
$image = Image::make($base64_image);

// Returns 0, looks like we have to encode image to get file size...
$image_size = strlen((string) $image);
Log::critical('image_size file size from string: ' . $image_size);

$image = $image->encode('jpg');

// Returns byte size
$image_size = strlen((string) $image);
Log::critical('image_size file size from string: ' . $image_size);

上述方法完美适用于小图像,但问题在于大图像。我想尽早检测到大小超过 10MB 限制,以免浪费任何内存/处理时间,并向用户返回图像超出允许的文件大小限制的错误。

当我以 base64 格式发送 100MB 图像时,Laravel 会抛出错误 PostTooLargeException,因为 post base64 的大小当然是巨大的。那么如何检测到实际图像超过了 10MB 的限制,如果超过,则向用户返回正常的错误?

【问题讨论】:

    标签: laravel-5 intervention


    【解决方案1】:

    这一行:

    $image = Image::make($base64_image);
    

    创建一个图像资源,当你将它转换为一个字符串时,它会给你一个空的。

    你需要得到实际字符串的长度,像这样:

    $image_size = strlen($base64_image);
    

    并检查它是否大于 10MB。

    【讨论】:

      【解决方案2】:

      普遍的共识是base64表示大约是原始图像的135%。如果字符串是 gzip 的,则可以更改。

      使用几个图像并将它们转换为 base64,使用或不使用 gzip 和 feom 计算出偏差百分比。

      【讨论】:

      • 对,我遇到了这个问题,但由于异常,我正试图在 Laravel 中专门处理这个问题。主要是在 Laravel 中检测该图像的 PostTooLargeException 并以优雅的错误响应。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-09-07
      • 2018-03-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多