我想在数据库中保存多个具有不同字段的图像文件,例如product_image
,feature_image
,slurp_image
。我使用以下控制器方法来保存图像文件
public function store(Request $request)
{
$product = new Product();
if($request->hasFile('product_image'))
{
$file = Input::file('product_image');
$imageName = time().'.'.$request->product_image->getClientOriginalExtension();
$product->product_image = $imageName;
$file->move('images/', $imageName);
}
if($request->hasFile('feature_image'))
{
$file = Input::file('feature_image');
$imageName = time().'.'.$request->feature_image->getClientOriginalExtension();
$product->feature_image = $imageName;
$file->move('images/', $imageName);
}
if($request->hasFile('slurp_image'))
{
$file = Input::file('slurp_image');
$imageName = time().'.'.$request->slurp_image->getClientOriginalExtension();
$product->slurp_image = $imageName;
$file->move('images/', $imageName);
}
// dd($product->product_image);
// dd($product->feature_image);
// dd($product->slurp_image);
$product->save();
}
当我dd()时$product->product_image
,$product->feature_image
,$product->slurp_image
我看到了不同的文件名,但是在它存储到数据库之后我看到同样的文件存储到不同的数据库中领域。
有谁帮忙找出可能是什么解决方案?
答案 0 :(得分:0)
当您一次上传多张图片时,您将通过一系列图片。
这是我之前完成此操作时的控制器功能。
public function multiple_upload() {
// get the files
$files = Input::file('images');
// counting of uploaded images
$file_count = count($files);
// start count how many uploaded
$uploadcount = 0;
foreach ($files as $file) {
$rules = array('file' => 'required'); //'required|mimes:png,gif,jpeg,txt,pdf,doc'
$validator = Validator::make(array('file'=> $file), $rules);
if($validator->passes()){
$destinationPath = 'uploads'; // upload folder in public directory
$filename = $file->getClientOriginalName();
$upload_success = $file->move($destinationPath, $filename);
$uploadcount ++;
// save into database
$extension = $file->getClientOriginalExtension();
$entry = new Uploads();
$entry->mime = $file->getClientMimeType();
$entry->original_filename = $filename;
$entry->filename = $file->getFilename().'.'.$extension;
$entry->save();
}
}
if($uploadcount == $file_count){
Session::flash('success', 'Upload successfully');
return Redirect::to('upload');
} else {
return Redirect::to('upload')->withInput()->withErrors($validator);
}
}
在你的例子中,我想象它会更像是这个
$product = new Product();
//upload multiple files
$files= [];
if($request->file('leftimage')) $files[] = $request->file('leftimage');
if($request->file('Middleimage')) $files[] = $request->file('Middleimage');
if($request->file('Rightimage')) $files[] = $request->file('Rightimage');
foreach($files as $file)
{
if(!empty($file))
{
$filename[] = $file->getClientOrginalName();
if(isset($filename)){
$file->move(base_path().'/frontend/sidimage/',end($filename));
}
}
$product->image1 = $filename[0];
$product->image2 = $filename[1];
$product->image3 = $filename[2];