php 批量下载文件

public function batchDownload()
    {
        $filename = 'tmp.zip';
        $zipName = date('YmdHi') . '.zip';
        $files = 'xxxx';//文件列表
        $zip = new \ZipArchive();
        $zip->open($filename, \ZipArchive::CREATE | \ZipArchive::OVERWRITE);
        $folder = base_path();//保存时需要去掉的父级文件夹
        foreach ($files as $item) {
            $filepath = base_path() . '/storage/' . $item['object_path'];
            //判断路径是否存在
            if (!is_file($filepath) || !file_exists($filepath)) {
                continue;
            }
            $filepath = str_replace('\\', '/', $filepath);
            $folder = str_replace('\\', '/', $folder);

            if (is_dir($filepath) === true) {
                $files = new \RecursiveDirectoryIterator($filepath, \RecursiveIteratorIterator::SELF_FIRST);
                foreach ($files as $file) {

                    $file = str_replace('\\', '/', $file);
                    if(in_array(substr($file, strrpos($file, '/') + 1), array('.', '..')))
                        continue;
                    if (is_dir($file) === true) {
                        $zip->addEmptyDir(str_replace($folder . '/', '', $file . '/'));
                    } else if (is_file($file) === true) {
                        $zip->addFromString(str_replace($folder . '/', '', $file), file_get_contents($file));
                    }
                }

            } else if (is_file($filepath) === true) {
                $zip->addFromString(basename($filepath), file_get_contents($filepath));
            }
            //$zip->addFile($filepath);

        }

        $zip->close();

        $file = fopen($filename, "r");
        Header("Content-type: application/octet-stream");
        Header("Accept-Ranges: bytes");
        Header("Accept-Length: " . filesize($filename));
        Header("Content-Disposition: attachment; filename=" . $zipName);
        while (!feof($file)) {
            fpassthru($file); // 输出至浏览器
            fclose($file);
            unlink($filename); //删除临时文件
            exit;
        }
    }

 

posted @ 2019-03-29 11:17  pengcx  阅读(2012)  评论(0编辑  收藏  举报