时空行者

  1. 首页
  2. PHP
  3. 正文

文件打包下载

2024年3月29日 932点热度
//data目录下file文件夹打包下载;
$zip = new ZipArchive;
$zipfile = "xyz.zip";
$savePath = "data/";
$dirName = "file";
$res = $zip->open($savePath .$zipfile, ZipArchive::CREATE);
if ($res === TRUE) {
//增加文件夹下多文件保持结构:注意文件夹存在
    addFileToZip($savePath, $zip);
    $zip->close();
    header("Cache-Control: public");
    header("Content-Description: File Transfer");
    header('Content-disposition: attachment; filename='.basename($zipfile)); //文件名
    header("Content-Type: application/zip"); //zip格式的
    header("Content-Transfer-Encoding: binary"); //告诉浏览器,这是二进制文件
    header('Content-Length: '. filesize($savePath.$zipfile)); //告诉浏览器,文件大小
    @readfile($savePath.$zipfile);
    removeFile($savePath.$dirName);
    @unlink($savePath.$zipfile);
} else {
    exit("fail zip:ZipArchive failure");
}
function addFileToZip($path, $zip,$savePath = '') {
    $handler = opendir($path);
    while (($filename = readdir($handler)) !== false) {
        if ($filename != "." && $filename != "..") {
            if (is_dir($path . "" . $filename)) {
                self::addFileToZip($path . "" . $filename."/", $zip);
            } else {
                $zip->addFile($path . "" . $filename,$savePath.$filename);
            }
        }
    }
    @closedir($path);
}
function removeFile($path){
    if(is_dir($path)){
        if($handle = opendir($path)){
            while($file = readdir($handle)){
                if(is_dir($path.'/'.$file) && $file != '.' && $file != '..'){
                } else {
                    if($file != '.' && $file != '..'){
                        @unlink($path.'/'.$file);
                    }
                }
            }
            closedir($handle);
        }
    }
}
标签: 暂无
最后更新:2024年4月9日

peakswill

这个人很懒,什么都没留下

点赞
< 上一篇
下一篇 >

COPYRIGHT © 2025 时空行者. ALL RIGHTS RESERVED.

Theme Kratos Made By Seaton Jiang

皖ICP备16014035号-3