【发布时间】:2019-01-09 08:42:01
【问题描述】:
我想用下面的代码下载一个 ZIP 格式的文件夹。
实际上,这非常适合仅用于压缩的下载文件夹。
但我希望 zip 文件也保存到公共/文件夹中的公共文件夹。 我使用 laravel 和 ziparchive
请帮帮我
public function downloadzip($id_pra) {
$dcmt = DB::table('document')->select(DB::raw(" max(id) as id"))->where('id_praapplication',$id_pra)->groupBy('type')->pluck('id');
$files = Document::whereIn('id', $dcmt)->get();
$url = url('')."/storage/uploads/file/".$id_pra."/";
# create new zip opbject
$zip = new \ZipArchive();
# create a temp file & open it
$tmp_file = tempnam('.','');
$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();
# 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.'-'.$url.'.zip');
header('Content-type: application/zip');
echo $tmp_file;
while (ob_get_level()) {
ob_end_clean();
}
readfile($tmp_file);
exit;
}
【问题讨论】:
-
你不能只使用
copy或file_put_contents函数(或其他)另外将文件写入相关位置然后发送文件吗? -
@常识,对不起,我的代码中遗漏了一些东西,已经更新为 $dcmt
-
$file->upload里面存储了什么?
标签: php laravel zip add ziparchive