Laravel - 超过 PHP 最大上传大小限制时验证文件大小

2021-12-24 00:00:00 file-upload php laravel

我的网站托管在共享服务器上.最大上传限制为 5MB.我无法更改 PHP ini 设置,这很好.

I have my website hosted at a shared server. The maximum upload limit is 5MB. I do not have the ability to change the PHP ini settings, which is fine.

在 Laravel 中,如果上传的文件小于 5MB,所有验证和文件上传都可以正常工作.但是,当上传大于 5MB 的文件时,我收到以下异常而不是验证错误:

In Laravel, all the validations and file uploading works fine if the uploaded file is under 5MB. However, when a file greater than 5MB is uploaded, I get the following exception instead of a validation error:

如何验证或强制文件低于服务器上传限制?

How can I validate or force the file to be under the upload limit from server?

推荐答案

您似乎对更改 PHP 限制以允许更大的文件不感兴趣.在我看来,您希望最大上传大小为 5MB,如果超过,则返回正确的响应.

You don't seem interested in changing the PHP limits to allow larger files. It looks to me like you want your max upload to be 5MB, and return a proper response if it is over that.

您可以在 app/Exceptions/Handler.php 处的异常处理程序中处理 FileException 异常.更新 render 方法以添加您需要的代码.例如,如果您想返回验证异常,则需要在 FileException 异常的异常处理程序中处理验证.

You can handle the FileException exception inside your exception handler at app/Exceptions/Handler.php. Update the render method to add in the code you need. For example, if you'd like to return a validation exception, you will need to handle the validation inside the exception handler for the FileException exception.

public function render($request, Exception $exception)
{
    if ($exception instanceof SymfonyComponentHttpFoundationFileExceptionFileException) {
        // create a validator and validate to throw a new ValidationException
        return Validator::make($request->all(), [
            'your_file_input' => 'required|file|size:5000',
        ])->validate();
    }

    return parent::render($request, $exception);
}

这是未经测试的,但应该可以让您大致了解.

This is untested, but should give you the general idea.

您还可以通过 javascript 进行客户端验证,这样过大​​的文件实际上永远不会发送到您的服务器,但是客户端可以禁用或删除 javascript,因此最好有一个不错的服务器端处理设置.

You can also do client side validation via javascript, so that a file that is too large is never actually sent to your server, but javascript can be disabled or removed by the client, so it would be good to have nice server side handling set up.

对于客户端验证,如果您将事件处理程序附加到文件输入的更改"事件,您可以使用 this.files[0].size 检查文件大小,并且之后执行任何其他操作(禁用表单、删除上传的文件等)

For the client side validation, if you attach an event handler to the "change" event for the file input, you can check the file size using this.files[0].size, and perform any additional actions after that (disable form, remove uploaded file, etc.)

相关文章