【发布时间】:2020-11-08 13:33:05
【问题描述】:
我想制作动态 zip,所以当管理员点击 .zip 时,它将根据用户 ud 下载并压缩文件夹中的所有文件 用户将拥有文档并使用其 ID 存储在文件夹中
即/public/stroage/file/ID001,所以当用户点击按钮下载时,它将强制下载ID0001.zip
这是我的代码
$zip = new \ZipArchive();
$uploaddir = public_path().'/temp';
$tmp_file = tempnam($uploaddir,'');
$zip->open($tmp_file, \ZipArchive::CREATE);
// Loop through each file
foreach($files as $file){
$url2 = $url.$file->upload;
$url2 = str_replace(' ', '%20', $url2);
if (!function_exists('curl_init')){
die('CURL is not installed!');
}
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url2);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$output = curl_exec($ch);
curl_close($ch);
$download_file = $output;
$type = substr($url2, -5, 5);
#add it to the zip
$zip->addFromString(basename($url.$file->upload.'.'.$type),$download_file);
}
// close zip
$zip->close();
// Set Time Download
date_default_timezone_set("Asia/Kuala_Lumpur");
$time_name = date('Ymd');
$time_download = date('Y-m-d H:i:s');
$log_download = new Log_download;
$user = Auth::user();
$id_user = $user->id;
$log_download->id_praapplication = $id_pra;
$log_download->id_user = $id_user;
$log_download->Activity = 'Download ZIP File';
$log_download->type = 'Zip Archive';
$log_download->downloaded_at = $time_download;
$log_download->save();
# send the file to the browser as a download
ob_start();
$strFile = file_get_contents($tmp_file);
header('Content-disposition: attachment; filename=DOC-'.$id_pra.'-'.'.zip');
header('Content-type: application/zip');
echo $tmp_file;
while (ob_get_level()) {
ob_end_clean();
}
readfile($tmp_file);
//$filetopath=$public_dir.'/'.$zipFileName;
//$filetopath = public_path().'/storage/uploads/file/'. $id_pra.'/'.$zipFileName;
// Create Download Response
// if(file_exists($filetopath)){
// return response()->download($filetopath,$zipFileName,$headers);
//}
exit;
实际上这段代码有效。但是我点击的每个下载 zip 的 utton 都会在文件夹 /public 中创建一个临时文件。 如何在不创建临时文件的情况下下载 zip,或者我可以创建 /public/tmp 之类的文件夹并将所有临时 zip 保存到该文件夹中?
【问题讨论】:
标签: php laravel public ziparchive tmp