美文网首页PHPThinkPHP
thinkphp5使用ZipArchive压缩多个文件夹带图片

thinkphp5使用ZipArchive压缩多个文件夹带图片

作者: 这真的是一个帅气的名字 | 来源:发表于2019-05-28 22:20 被阅读0次

    使用的TP框架,以及PHP自带的压缩类ZipArchive
    展示效果


    image.png image.png image.png
        public function testzip()
        {
            $imgs = array(
                "4" => array(
                    'https://ss3.baidu.com/9fo3dSag_xI4khGko9WTAnF6hhy/image/h%3D300/sign=b74adc2efddeb48fe469a7dec01e3aef/b812c8fcc3cec3fdb6b3e13ad888d43f869427eb.jpg',
                    'https://ss2.baidu.com/-vo3dSag_xI4khGko9WTAnF6hhy/image/h%3D300/sign=8c46925c297f9e2f6f351b082f31e962/500fd9f9d72a605908e0c1a02634349b023bba93.jpg',
                    'https://ss0.baidu.com/7Po3dSag_xI4khGko9WTAnF6hhy/image/h%3D300/sign=0fcb287ab4a1cd111ab674208913c8b0/b219ebc4b74543a97531368610178a82b9011456.jpg',
                ),
                "7" => array(
                    'https://ss3.baidu.com/-fo3dSag_xI4khGko9WTAnF6hhy/image/h%3D300/sign=52ecd2493a9b033b3388fada25cf3620/77c6a7efce1b9d167b3c552cfddeb48f8d546480.jpg',
                    'https://ss2.baidu.com/-vo3dSag_xI4khGko9WTAnF6hhy/image/h%3D300/sign=f978ff2b9aeef01f52141ec5d0ff99e0/c2fdfc039245d68899c8f4ebaac27d1ed31b24b2.jpg',
                )
            );
            $name = "test";
            $filename = ROOT_PATH . 'public/uploads/downzip/' . $name . '.zip';
            $downname = $name . '.zip';
            $zip = new \ZipArchive();
            if ($zip->open($filename, \ZIPARCHIVE::CREATE) !== TRUE) {
                exit('无法打开文件,或者文件创建失败');
                return 0;
            }
            foreach ($imgs as $key => $val) {
                $i = 1;
                foreach ($val as $k => $v) {
                    $zip->addFromString($key . '/' . $i . '.jpg', file_get_contents($v));
                    $i++;
                }
            }
            $zip->close();
            $fp = fopen($filename, "r");
            $file_size = filesize($filename);//获取文件的字节
    
            header("Content-type: application/octet-stream");
            header("Accept-Ranges: bytes");
            header("Accept-Length:" . $file_size);
            header("Content-Disposition: attachment; filename=$downname");
            $buffer = 1024; //设置一次读取的字节数,每读取一次,就输出数据(即返回给浏览器)
            $file_count = 0; //读取的总字节数
            while (!feof($fp) && $file_count < $file_size) {
                $file_con = fread($fp, $buffer);
                $file_count += $buffer;
                echo $file_con;
            }
            fclose($fp);
    
        }
    

    相关文章

      网友评论

        本文标题:thinkphp5使用ZipArchive压缩多个文件夹带图片

        本文链接:https://www.haomeiwen.com/subject/uwtstctx.html