Laravel 5.5-为大型base64图像处理PostTooLargeException吗? [英] Laravel 5.5 - Handling PostTooLargeException for large base64 image?
问题描述
每个图片我只能接受10MB的存储空间,任何较大的存储空间都将阻止代码执行.我不确定该怎么做.这是我尝试过的:
I have a limit of 10MB to accept per image and anything larger should prevent execution of the code. I am not sure how to do so. Here is what I tried:
在控制器方法中:
// 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,以免浪费任何内存/处理时间,而只是向用户返回一个错误,即图像超出了允许的文件大小限制.
The above works with small images perfectly, but the issue is with large images. I want to detect as early as possible that the size is over the 10MB limit as to not waste any memory/processing time and just return an error to the user that the image is above the allowed file size limit.
当我发送100MB图像作为base64时,Laravel抛出错误
PostTooLargeException
,因为后base64的大小当然很大.那么,如何检测实际图像超出10MB的限制,并向用户返回一个优美的错误?
When I send a 100MB image as base64, Laravel throws an error of
PostTooLargeException
, since of course the size of the post base64 is huge. So how can I detect that the actual image is over the 10MB limit and return a graceful error to the user if it is?
推荐答案
此行:
$image = Image::make($base64_image);
创建一个图像资源,当您将其转换为字符串时,它会为您提供一个空的图像资源.
creates a image resource, and when you cast it to a string it gives you an empty one.
您需要获取实际字符串的长度,如下所示:
You need to get the length of the actual string, like this:
$image_size = strlen($base64_image);
并检查它是否大于10MB.
and check if it's bigger than 10MB.
这篇关于Laravel 5.5-为大型base64图像处理PostTooLargeException吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!