以下代码用于解压缩文件,然后验证并保存在数据库中。
public function unzip_contents_gallery(Request $request)
{
try{
$v = [];
$allowed_exts = [
'png',
'jpeg',
'jpg',
'webp',
];
$zip = new ZipArchive();
$status = $zip->open($request->file("zip_gallery")->getRealPath());
if ($status !== true)
throw new Exception('Un-supported zip archive');
for($i=0; $i<$zip->count();$i++)
{
array_push($v, ['name' => $zip->getNameIndex($i)]);
$ext_name_arr = explode('.', $zip->getNameIndex($i));
if(!(in_array(end($ext_name_arr), $allowed_exts)))
throw new Exception('File not supprted!');
}
$rules = [
'*.name' => 'required|unique:galleries,gallery',
];
$validator = Validator::make($v, $rules);
if($validator->fails())
throw new Exception(json_encode($validator->errors()->all()));
// throw new Exception($validator->errors()->first());
$storageDestinationPath = public_path('uploads/gallery_images');
if (!\File::exists( $storageDestinationPath)) {
\File::makeDirectory($storageDestinationPath, 0755, true);
}
$zip->extractTo($storageDestinationPath);
$zip->close();
for($i=0; $i<count($v);$i++)
{
Gallery::create([
'gallery' => $v[$i]
]);
}
$msg = "File Upload Successfully";
return redirect()->back()->withSuccess($msg);
}
catch(Exception $e)
{
return redirect()->back()->withErrors($e->getMessage());
}
}