打包文件下载的主要思路:
在附件表中存的是文件的地址,地址存成这样****的:
./Public/Uploads/File/5d906c309e4bc.docx【注意前面的 . 】 也是为方便后面的操作
1.指定压缩包的的名称
2.创建文件夹存放需要下载的文件(可指定文件的下载后的名称)
下载后的文件我用的原名称,这个点是需要改善的,不然解压压缩包后的文件名是一些被编码后的名称(像这样:5d906c309e4bc.docx)用户体验不是很好,之前考虑在上传文件的时候考虑将原文件名也带上,但没能实现。
直接上代码:
<?php
class PackageloadAction extends Action{
function download(){
$zipname = './FILE.zip'; // 压缩包名称用中文可能不能识别,可以设置编码方式看看
$attach=M("attachment");
$where['attrelatedid']=$_GET['id'];
$where['atttype']=$_GET['tab'];
$filearr=$attach->where($where)->field("path")->select();
$down_patha=array();
$i=0;
foreach ($filearr as $arr){
$down="file/";
$path=explode("/",$arr['path']);
array_push($filearr[$i++],$down.$path[4]);
}
//要使用该类,需要先启用 extension=php_zip.dll
$zip = new \ZipArchive ();
$res = $zip->open ( $zipname, \ZipArchive::CREATE );
if ($res === TRUE) {
//这里将服务器上的文件添加到下载内容中,并重新赋值下载zip文件内该文件的路径
foreach ($filearr as $arr){
$zip->addFile ( $arr["path"],$arr["0"]);
}
}
$zip->close ();
header ( "Content-Type: application/zip" );
header ( "Content-Transfer-Encoding: Binary" );
header ( "Content-Length: " . filesize ( $zipname ) );
header ( "Content-Disposition: attachment; filename=\"" . basename ( $zipname ) . "\"" );
readfile ( $zipname );
//如不删除,则在服务器上会有 $zipname 这个zip文件
@unlink ( $zipname );
}
}
?>
补充说明:
foreach ($filearr as $arr){
$zip->addFile ( $arr["path"],$arr["0"]);
}
如果对这个二维文件数组有其他要求的看上一篇对二维的操作。