php文件打包下载
html代码
前端请求php,传参需要打包的文件标识,php压缩完成返回文件路径
$("#content").on('click','.download',function(){
var url =[];
$(this).siblings("input[type=hidden]").each(function(){
url.push($(this).val());
})
$.ajax({
url:"zipfile.php?action=downloadzip",
data:{'url':url},
type:"POST",
dataType:'json',
async:false,
success:function(data){
if(data==0){
alert('压缩失败');
}else{
window.open('downloadUrl.php?url='+data, "_blank");
}
}
});
});
php代码
压缩文件
$file = $_POST['url'];
//这里需要注意该目录是否存在,并且有创建的权限
$zipname = '../file/'.time().'.zip';
//这是要打包的文件地址数组
$files = $file;
$zip = new ZipArchive();
$res = $zip->open($zipname, ZipArchive::CREATE);
if ($res === TRUE) {
foreach ($files as $file) {
$new_filename = substr($file, strrpos($file, '/') + 1);
$zip->addFile($file, $new_filename);
}
}
//关闭文件
$zip->close();
if($zipname){
echo json_encode($zipname);
}
下载文件
function download($file){
header('Content-Type:application/octet-stream');
$fileName=basename($file);
header('Content-Disposition:attachment;filename="'.$fileName.'"');
$buffer='';
$cnt=0;
$handle=fopen($file,'rb');
if($handle===false){
return false;
}
while(!feof($handle)){
$buffer=fread($handle,1024*1024);
echo $buffer;
ob_flush();
flush();
if($retbytes){
$cnt+=strlen($buffer);
}
}
$status=fclose($handle);
if($retbytes&&$status){
return $cnt;
}
return $status;
}
$file = $_GET['url'];
if (!empty($file)) {
download($file);
unlink($file);
}