最后我可以上传和移动图片,但现在我想在Laravel上创建多个上传图片。那可能吗?我是否必须使用数组来制作它?
我可以从这段代码中稍微修改一下吗?
它在我的ProductController.php
上$picture = '';
if ($request->hasFile('images')) {
$file = $request->file('images');
$filename = $file->getClientOriginalName();
$extension = $file->getClientOriginalExtension();
$picture = date('His').$filename;
$destinationPath = base_path() . '\public\images/';
$request->file('images')->move($destinationPath, $picture);
}
if (!empty($product['images'])) {
$product['images'] = $picture;
} else {
unset($product['images']);
}
谢谢。 注意:上面的代码来自stackoverflow上的一个善良的人,再次感谢;)
答案 0 :(得分:14)
在您的前端表单中,您必须使用您的字段属性名称,如
name="images[]"
你的控制器代码就是这样。
$picture = '';
if ($request->hasFile('images')) {
$files = $request->file('images');
foreach($files as $file){
$filename = $file->getClientOriginalName();
$extension = $file->getClientOriginalExtension();
$picture = date('His').$filename;
$destinationPath = base_path() . '\public\images';
$file->move($destinationPath, $picture);
}
}
if (!empty($product['images'])) {
$product['images'] = $picture;
} else {
unset($product['images']);
}
答案 1 :(得分:3)
来自$ _POST的输入将作为数组进入。您需要做的就是遍历它:
$picture = '';
if ($request->hasFile('images')) {
$files = $request->file('images');
foreach($files as $file){
$filename = $file->getClientOriginalName();
$extension = $file->getClientOriginalExtension();
$picture = date('His').$filename;
$destinationPath = base_path() . '\public\images/';
$request->file('images')->move($destinationPath, $picture);
}
}
答案 2 :(得分:0)
稍加修改的代码即可上传多张图片。
public function store(Request $request)
{
$pid = $request->input('pid');
$input = $request->file('images');
$picture = array();
if($request->hasFile('images')) :
foreach ($input as $item):
$extension = $item->getClientOriginalName();
$name = date('Ymd') . '.' . $extension;
$destinationPath = base_path() . '/uploads/images/';
$item->move($destinationPath, $name);
$arr[] = $name;
endforeach;
$picture = implode(",", $arr);
else:
$picture = '';
endif;
DB::table('document')->insert(array('pid' => $pid,'image' => $picture));
Session::flash('message', 'Multiple pictures are uploaded successfully');
return redirect('/image-upload');
}