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.

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:

FileException - The file

如何验证或强制文件处于服务器的上载限制之下?

推荐答案

您似乎对更改PHP限制以允许更大的文件不感兴趣.在我看来,你希望你的最大上传量为5MB,如果超过这个上限,你会返回一个正确的回复.

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 \Symfony\Component\HttpFoundation\File\Exception\FileException) {
        // 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,所以最好设置好服务器端处理.

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

Laravel相关问答推荐

如何通过 Eloquent 获取单个集合中每位教师的学生人数

如何从laravel中的另一个表中获取用户名

Laravel 9:AWS S3 检索要流式传输的视频

使用命令行界面停止 laravel 服务器

如何在 laravel 中安装 PHPExcel 库?

为什么我的 Laravel 队列作业(job)在 60 秒后失败?

Laravel 中间件 except除外规则不起作用

在 Laravel 中下载后如何重定向?

不支持驱动Driver[] - Laravel 5.3

Laravel - 自定义时间戳列名称

加载模型的所有关系

禁用Eager的关系

安装后在 Lumen 中找不到页面

Laravel 字符串验证以允许空字符串

如何在 Laravel 4 中组织不同版本的 REST API 控制器?

laravel 如何读取 app/config/app.php 调试变量

Laravel 验证存在于不存在的地方

将图像保存在公共文件夹中,而不是存储 laravel 5

将参数传递给过滤器 - Laravel 4

在 Laravel 中软删除父记录时如何软删除相关记录?