使用 laravel 5.7 将多张图片上传到数据库

Upload multiple images into database using laravel 5.7

我想上传多张图片并将它们存储到数据库中,但我遇到了这样的错误:

file_get_contents() expects parameter 1 to be a valid path, array given

这是我的控制器:

public function fileMultiple(Request $request) {
        $this->validate($request, [
            'filename.*' => 'image|mimes:jpeg,png,jpg,gif,svg|max:2048'
        ]);

        if($request->hasfile('filename'))
         {

            foreach($request->file('filename') as $image)
            {
                $name=$image->getClientOriginalName();
                $image_encod = base64_encode(file_get_contents($request->file('filename')));
                $destinationPath = public_path('/images');
                $image->move($destinationPath, $name);

                $data = new Image();
                $data->image_name = $image_encod;
                $data->save();

            }
         }

        return back()->with('success', 'Your images has been successfully');
    }

如何解决,图片必须使用base64编码

问题在于您发送的是数组值。

以下代码:

$image_encod = base64_encode(file_get_contents($request->file('filename')));

应改为:

$image_encod = base64_encode(file_get_contents($image));
<?php 

public function fileMultiple(Request $request) {

    $this->validate($request, [
        'filename.*' => 'image|mimes:jpeg,png,jpg,gif,svg|max:2048'
    ]);

    if(is_array($request->filename) && count($request->filename) > 0){

        foreach ($request->filename as $key => $file) {

            if($request->hasFile('filename.' . $key)){

                $file = $request->file('filename.' . $key);

                if($file->store(public_path('/images')))
                {
                    $data = new Image();
                    $data->image_name = $image_encod;
                    $data->save();

                    return back()->with('success', 'Your images has been successfully');
                }
                else{
                    throw new \Exception('Unable to save image.');
                }
            }
        }
    }

    return back()->with('error', 'Unable to save image.');
}

您可以简单地在 foreach 循环中稍微更改一下,然后通过以下方式使用 $key

foreach($request->file('filename') as $key => $image)
{
   $name=$image->getClientOriginalName();
   $image_encod = base64_encode(file_get_contents($request->file('filename')[$key]));
   $destinationPath = public_path('/images');
   $image->move($destinationPath, $name);

   $data = new Image();
   $data->image_name = $image_encod;
   $data->save();

}