Laravel 5.5 图像数组上的“文件必须是图像”

问题描述 投票:0回答:3

我正在开发一个 Laravel 5.5 项目,该项目给了我一些问题...其中之一是,当我上传一些图像时,它返回一个错误:“该文件必须是图像”,并在控制器。`

public function update(\App\Property $property, Request $request)
{
    $rules = [ 
        'images.*' => 'mimes:image|max:2048',
        'zone' => 'required'
    ];

    $messages = [
        'images.mimes' => 'The file must be an image', // in my file that is a translated of the original message
        'images.max' => 'The images sizes must be under 2MB',
    ];

 $validator = Validator::make($request->all(), $rules, $messages);

    if($validator->fails()) {
        parent::message(
            $validator->errors(),
            '¡Error!',
            'error'
        );

        return back()->withInput();
    }


以防万一:

我正在读一些有同样问题的人,但就我而言,我有通常的

<form method="POST action="..." enctype="multipart/form-data">

我根据要求做了一个

dd($request->files)
,但我上传的所有图像似乎都是图像。

我也尝试使用迭代方法如下:

    if($request->hasFile('images')) {
        foreach ($images as $image)
        {
            $validator = Validator::make(
                [ 'image' => $image ], 
                [ 'image' => 'mimes:jpeg,png,jpg,gif,svg|max:2048' ],
                [ 
                    'image.mimes' => 'Images must have format (JPEG, PNG, JPG, GIF or SVG)',
                    'image.max' => 'Each image must be under 2MB' 
                ]);

            if($validator->fails()) {
                parent::message(
                    $validator->errors(),
                    '¡Error!',
                    'error'
                );

                return back()->withInput();
            }
        }
    }

但是当图像大于 2MB 时,请求甚至不会通过

if($request->hasFile() function
。 我想要所有图像的通用错误,而不是验证每个图像,这可能吗?顺便说一句,在 Laravel 文档 中没有以前的迭代方法。

php laravel validation laravel-5
3个回答
5
投票

我也试图弄清楚这一点,似乎 symfony 自 Laravel 5.5 以来已经更新了。在 Laravel 8 上,我可以告诉您以下设置组合修复了我遇到的错误,并产生了与您相同的错误类型: 在你的表格中: 确保您的表格有

<form method="POST action="..." enctype="multipart/form-data">

在您的验证器中:

'image' =>  'required|image|mimes:jpeg,png,jpg,gif,svg|max:2048',

0
投票

如果您在表单中使用 Laravel Collectives,那么您可以实现 enctype,如下所示:

{!! Form::open([‘action’ =>’ProfilesController@update’, 
‘method’ => ‘POST’, ‘enctype’ => ‘multipart/form-data’]) !!}

0
投票

我遇到了类似的问题,并通过将图像更改为文件并指定图像文件类型来修复它。

'images' => 'file|mimes:jpeg,png,jpg|max:2048'

就你而言,

$rules = [ 
        'images.*' => 'file|mimes:jpeg,png,jpg|max:2048',
        'zone' => 'required'
    ];
© www.soinside.com 2019 - 2024. All rights reserved.