您的位置:首页 > 编程语言 > PHP开发

php打包下载文件

2015-09-22 10:21 681 查看
使用前请先开启:查看下php.ini里面的extension=php_zip.dll前面的分号有没有去掉;

$zip=new \ZipArchive();
$zifile = 'download/' . $bookid . '.zip';//压缩包名字
if($zip->open($zifile, \ZipArchive::OVERWRITE)=== TRUE){
$this->addFileToZip('download/'.$bookname, $zip); //调用方法,对要打包的根目录进行操作,并将ZipArchive的对象传递给方法
$zip->close(); //关闭处理的zip文件
}

//添加文件方法
function addFileToZip($path,$zip){
//echo $path;
$handler=opendir($path); //打开当前文件夹由$path指定。
while(($filename=readdir($handler))!==false){
//var_dump($filename);continue;
if($filename != "." && $filename != ".."){//文件夹文件名字为'.'和‘..’,不要对他们进行操作
if(is_dir($path."/".$filename)){// 如果读取的某个对象是文件夹,则递归
$this->addFileToZip($path."/".$filename, $zip);
}else{ //将文件加入zip对象
//echo $path."/".$filename.'<br>';
$a=substr($path."/".$filename,strlen('download/'));
//$zip->addFile($path."/".$filename);
$zip->addFile($path."/".$filename,$a);
}
}
}
@closedir($path);
}


下载文件

$this->download ($zifile,' '.$bookname . '.zip');

/**
* 可以指定下载显示的文件名,并自动发送相应的Header信息
* 如果指定了content参数,则下载该参数的内容
* @static
* @access protected
* @param string $filename 下载文件名
* @param string $showname 下载显示的文件名
* @param integer $expire  下载内容浏览器缓存时间
* @return void
* @throws ThinkExecption
*/
protected  function download ($filename, $showname='',$expire=180) {
if(file_exists($filename)){
$length = filesize($filename);
}elseif(is_file(UPLOAD_PATH.$filename)){
$filename = UPLOAD_PATH.$filename;
$length = filesize($filename);
}else {
throw_exception($filename.L('下载文件不存在!'));
}
if(empty($showname)){
$showname = $filename;
}
$showname = basename($showname);
if(empty($filename)){
$type = mime_content_type($filename);
}else{
$type = "application/octet-stream";
}
ob_end_clean();
//发送Http Header信息 开始下载
header("content-type:text/html; charset=utf-8");
header("Pragma: public");
header("Cache-control: max-age=".$expire);
//header('Cache-Control: no-store, no-cache, must-revalidate');
header("Expires: " . gmdate("D, d M Y H:i:s",time()+$expire) . "GMT");
header("Last-Modified: " . gmdate("D, d M Y H:i:s",time()) . "GMT");
//下面一行就是改动的地方,即用iconv("UTF-8","GB2312//TRANSLIT",$showname)系统函数转换编码为gb2312
header("Content-Disposition: attachment; filename=". iconv("UTF-8","gb2312",$showname));
header("Content-Length: ".$length);
header("Content-type: ".$type);
header('Content-Encoding: none');
header("Content-Transfer-Encoding: binary" );
ob_clean();
readfile($filename);
//exit();
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: