//清空路径下的所有文件
delete_dir(public_path() . "/upload/data/");
$res = Evidence::whereIn("id", $this->data['evidences_id'])
->get();
foreach ($res as $v) {
$type = $v->file_md5;
$file_url = $v->upload_path;
if (!is_dir(public_path() . "/upload/data/")) mkdir(public_path() . "/upload/data/", 0777);
$dir = public_path() . "/upload/data/{$type}";
if (!is_dir($dir)) mkdir($dir, 0777);
//把远程文件下载到本地文件夹中 最多3次否则判断下载失败
$n = 0;
do {
if (@copy(trim($file_url), public_path() . "/upload/data/{$type}/" . basename($file_url))) {
break;
} else {
$n++;
sleep(1);
if ($n >= 3) {
Download::where("id", $this->download->id)->update(["status" => 2, "error_msg" => "文件下载失败"]);
break;
}
}
} while (true);
}
//2.打包下载本地文件夹
//初始化zip 名字
$zipName = date("YmdHis") . 'file.zip';
$zip_file = str_replace("\\", '/', public_path("download/$type")) . $zipName;
$zip = new \ZipArchive();
$zip->open($zip_file, \ZipArchive::CREATE | \ZipArchive::OVERWRITE);
//将被压缩文件夹
$path = str_replace("\\", '/', public_path("upload/data/{$type}"));
if (count($res) > 1) {
$path = str_replace("\\", '/', public_path("upload/data/"));
}
//迭代器
$files = new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($path));
foreach ($files as $file) {
//跳过所有子目录
if (!$file->isDir()) {
//获取文件路径
$filePath = $file->getRealPath();
//获取文件名
$fileName = $file->getFilename();
// $zip->addFile($filePath, $fileName);
$fp = fopen($filePath, "rb", 0);
$arr = explode('\\', $filePath);
$dir = $arr[count($arr) - 2];
$images = fread($fp, filesize($file));
$zip->addFromString("$dir/" .$fileName, $images);
}
}
$zip->close();
$url = config('app.url') . "download/$type$zipName";
chmod($zip_file, 0777);
Download::where("id", $this->download->id)->update(["status" => 1, "path" => $url]);
// return response()->download($zip_file, $zipName)->deleteFileAfterSend(true);//下载生成的zip文件
|