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

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

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

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

php laravel laravel-5.2
3个回答
2
投票

问题是,你要发送的数组值。

下面的代码:

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

应改为:

$image_encod = base64_encode(file_get_contents($image));

3
投票

你可以简单地改变foreach循环一点点,按照使用$键:

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();

}

0
投票
<?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.');
}
© www.soinside.com 2019 - 2024. All rights reserved.