我正在使用Laravel中的干预调整器将多幅上传图像制作到数据库中。
这就是我现在在控制器中编码的内容
imgProdukProc
控制器:
use Illuminate\Http\Request;
use File;
use Image;
use App\imgProd;
.....
public function store(Request $request)
{
if($request->hasFile('img')){
foreach ($request->file('img') as $image) {
if ($image->isValid()) {
$img = new imgProd();
$image_name = uniqid() .'.'. $image->getClientOriginalExtension();
$path = public_path('/img/prod');
$imgx = Image::make($image->getRealPath());
$imgx->resize(360, 360, function ($constraint) {
$constraint->aspectRatio();
})->save($path.'/'.$image_name);
$img->id_prod = $request->get('id_prod');
$img->pics = 'img/prod/'.$image_name;
$date=date_create('now');
$format = date_format($date,"Y-m-d");
$img->date = $format;
$img->save();
return redirect('adminImgProd')->with('success', 'Picture successfully added ');
}
}
}
}
这是我的观点
adminImgProd视图
<form enctype="multipart/form-data" action="{{url('adminImgProd')}}" method='post'>
@csrf
<div class="form-group">
<label>CODE PRODUCT</label>
<div class="input-group">
<span class="input-group-addon"><span class="glyphicon glyphicon-pencil"></span></span>
<input type="text" autocomplete="off" class="form-control" id='id_prod' name='id_prod' required="required" />
<span class="input-group-addon"><button type="button" onClick="javascript:openWindow2();">Select</button></span>
</div>
</div>
<div class="form-group">
<label>IMAGE PRODUCT</label>
<div class="input-group">
<span class="input-group-addon"><span class="glyphicon glyphicon-pencil"></span></span>
<input multiple type="file" class="form-control" name='img[]' id='file-input' required="required" /></div>
</div>
上面的代码可以正常工作,但是以某种方式,当我尝试上传2张图像或3张图像时,保存在目标文件夹和数据库中的唯一图像只是一个,而最后一个是
我的代码错误在哪里,或者仅仅是我的代码从一开始就是错误的?
提前谢谢
答案 0 :(得分:1)
您将return
放入了foreach
中,因此在1次循环之后,它将返回并退出您的函数:
public function store(Request $request)
{
if ($request->hasFile('img')){
foreach ($request->file('img') as $image) {
if ($image->isValid()) {
$img = new imgProd();
$image_name = uniqid() .'.'. $image->getClientOriginalExtension();
$path = public_path('/img/prod');
$imgx = Image::make($image->getRealPath());
$imgx->resize(360, 360, function ($constraint) {
$constraint->aspectRatio();
})->save($path.'/'.$image_name);
$img->id_prod = $request->get('id_prod');
$img->pics = 'img/prod/'.$image_name;
$date=date_create('now');
$format = date_format($date,"Y-m-d");
$img->date = $format;
$img->save();
}
}
return redirect('adminImgProd')->with('success', 'Picture successfully added ');
}
}
答案 1 :(得分:0)
您可以对多张图片执行以下操作:
$images = $request->file('images');
foreach ($images as $key => $image) {
if ($request->hasFile('images') && $request->file('images')[$key]->isValid()) {
$path = $request->images[$key]->store('public/images');
$path = basename($path);
$image = new ProductImages();
$image->product_id = $request->get('product_id');
$image->photo = $path;
$image->save();
}
}
我希望这会有所帮助。