在我的Laravel应用中,我具有保存多个图像以保存上载表的表单,表单如下,
<form method="post" action="{{url('form')}}" enctype="multipart/form-data">
{{csrf_field()}}
<div class="form-group row required">
<div class="field" align="left" >
<h3>Upload images</h3>
<input type="file" class="files" name="files[]" multiple />
<input type="file" class="files" name="files[]" multiple />
<input type="file" class="files" name="files[]" multiple />
<input type="file" class="files" name="files[]" multiple />
</div>
</div>
和控制器存储功能是
$photos = $request->file('files');
if (!is_array($photos)) {
$photos = [$photos];
}
if (!is_dir($this->photos_path)) {
mkdir($this->photos_path, 0777);
}
for ($i = 0; $i < count($photos); $i++) {
$photo = $photos[$i];
$name = sha1(date('YmdHis') . str_random(30));
$save_name = $name . '.' . $photo->getClientOriginalExtension();
$resize_name = $name . str_random(2) . '.' . $photo->getClientOriginalExtension();
Image::make($photo)
->resize(250, null, function ($constraints) {
$constraints->aspectRatio();
})
->save($this->photos_path . '/' . $resize_name);
$photo->move($this->photos_path, $save_name);
$upload = new Upload();
$upload->filename = $save_name;
$upload->resized_name = $resize_name;
$upload->original_name = basename($photo->getClientOriginalName());
$upload->vehicle_id = $vehicle->id;
$upload->save();
return redirect()->route('categories.categorypost')->with('info','Your Advertisment has been created successfully');
}
}
但是当我以上述形式附加4张图像时。它仅保存一张图像。附加到第一个输入文件。为什么其他图像没有保存到表中。但是当我删除返回以下代码
return redirect()->route('categories.categorypost')->with('info','Your Advertisment has been created successfully');
然后我可以保存所有图像。但是我需要上面的控制器返回并保存所有图像。我该怎么办?
答案 0 :(得分:0)
您的重定向位于for循环中,该循环迭代图像并保存它们,您必须将重定向置于for循环之后,否则您将在保存第一个图像后被重定向:
for ($i = 0; $i < count($photos); $i++) {
$photo = $photos[$i];
$name = sha1(date('YmdHis') . str_random(30));
$save_name = $name . '.' . $photo->getClientOriginalExtension();
$resize_name = $name . str_random(2) . '.' . $photo->getClientOriginalExtension();
Image::make($photo)
->resize(250, null, function ($constraints) {
$constraints->aspectRatio();
})
->save($this->photos_path . '/' . $resize_name);
$photo->move($this->photos_path, $save_name);
$upload = new Upload();
$upload->filename = $save_name;
$upload->resized_name = $resize_name;
$upload->original_name = basename($photo->getClientOriginalName());
$upload->vehicle_id = $vehicle->id;
$upload->save();
}
return redirect()->route('categories.categorypost')->with('info','Your Advertisment has been created successfully');