我想上传多张图像并将其存储到数据库中,但是出现了这样的错误:
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编码
答案 0 :(得分:3)
您只需在 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();
}
答案 1 :(得分:2)
问题是您正在发送数组值。
以下代码:
$image_encod = base64_encode(file_get_contents($request->file('filename')));
应更改为:
$image_encod = base64_encode(file_get_contents($image));
答案 2 :(得分: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.');
}