php 文件夹压缩下载、文件压缩下载(附源码)

public function getRequestZipDownLoad($request){
        // 获取选中的 ID 
        $fileIds = explode(',',$_POST['zipDownId']);
        // 获取选择下载的是 哪一种文件
        $isDownLoad = $_POST['isDownLoad'];
        $zip = new \ZipArchive();
        foreach ($fileIds as $value) 
        {
            // 校验数据是否存在
            $relevance = $this->getLdAsrService()->asrGetByFields(
                ['fileId' => $value,'type'=>'cloud','status'=>'finished']
            );
            if(empty($relevance)){
                return $this->createJsonResponse(['message' => '未生成字幕', 'code' => -2]);
            }
            // 校验 下载格式
            if (in_array('1',$isDownLoad) && in_array('2',$isDownLoad)) {
                $this->SrtDownLoadZipFormat($zip,$relevance,$value);
                $this->WordDownLoadZipFormat($zip,$relevance);
                // 下载格式为 word + srt 格式
                // 把两个 压缩好的 压缩包 再放进一个新的压缩包里,然后再去下载
                if($zip->open($this->srtWordDown, ZIPARCHIVE::CREATE) !== true) {
                    return false;
                }
                if(file_exists($this->srtDown) && file_exists($this->wordDown)){
                    $zipArray = [$this->srtDown,$this->wordDown];
                    foreach($zipArray as $v){
                        $zip->addFile($v,basename($v));
                    }
                }
            }else if (in_array('1',$isDownLoad)) {
                // 下载格式为 srt 格式
                $this->SrtDownLoadZipFormat($zip,$relevance,$value);
            }else if (in_array('2',$isDownLoad)) {
                // 下载格式为 word 格式
                $this->WordDownLoadZipFormat($zip,$relevance);
            }
        }
        $host = $request->getSchemeAndHttpHost();
        $url = $host .'/lddev.php/course_set/manage/batch/packDownload';
        // $url = 'http://www.lingdaipc.win/lddev.php/course_set/manage/batch/packDownload';
        return $this->createJsonResponse(['data' => $url]);
    }
/**
     * Author:FYC
     * TIme:2023年6月30日
     * Description : 下载 word 格式文件的封装方法
    */
    public function WordDownLoadZipFormat($zip,$relevance){ 
        // 打开压缩包
        if($zip->open($this->wordDown, ZIPARCHIVE::CREATE) !== true) {
            return false;
        }
        $subtitleData = json_decode($relevance['subtitleData'], true);
        // 生成的word存放地址
        if ($relevance['type'] == 'cloud' && empty($relevance['fileName'])) {
            $file = $this->getUploadFileService()->getFile($relevance['fileId']);
            $filename = str_replace(strrchr($file['filename'], "."), "", $file['filename']) . '.docx';
        }else{
            $filename = str_replace(strrchr($relevance['fileName'], "."), "", $relevance['fileName']) . '.docx';
        }
        $subtitleText = '';
        foreach ($subtitleData as $subtitle)
        {
            $subtitleText .= $this->processSpecialChars($subtitle['text']);
        }
        // 开启缓冲区
        ob_start();
        // 输出内容
        echo $subtitleText;
        // 得到输出内容
        $data = ob_get_contents();
        // 关闭缓冲区
        ob_end_clean();
        // 打开文件  没有会创建
        $fp = fopen($filename,"wb");
        // 写入文件
        fwrite($fp,$data);
        // 关闭文件
        fclose($fp);
        // 把文件放入压缩包
        $zip->addFile($filename,basename($filename));
        $zip->close();
        unlink(basename($filename));
    }
 /**
     * Author:FYC
     * TIme:2023年6月30日
     * Description : 下载 srt' 格式文件的封装方法
    */
    public function SrtDownLoadZipFormat($zip,$relevance,&$value,$isFalg = null){
        $file = $this->getUploadFileService()->getFile($value);
        $srtName = $file['globalId'] . '.' . 'srt';
        $path = $this->getBiz()['topxia.upload.public_directory'] . '/zipDownLoad/srt/';
        if(!is_dir($path)){
            mkdir($path,0777,true);
        }
        $pathName = $this->getBiz()['topxia.upload.public_directory'] . '/zipDownLoad/srt/'. $srtName;
        $this->asrGeneralClient = new General($this->getBiz());
        $this->asrGeneralClient->jsonToSrt(
            json_decode($relevance['subtitleData'], true),
            $pathName
        );
        $this->dirToZip([$path],$this->srtDown);
        $this->deleteDirectory($path);

        // $file = $this->getUploadFileService()->getFile($value);
        // $srtName = $file['globalId'] . '.' . 'srt';
        // $path = $this->getBiz()['topxia.upload.public_directory'] . '/AsrFiles'
        //     . '/' . $value . '/' . $srtName;
        // $this->asrGeneralClient = new General($this->getBiz());
        // $this->asrGeneralClient->jsonToSrt(
        //     json_decode($relevance['subtitleData'], true),
        //     $path
        // );
        // $file = $this->get('kernel')->getProjectDir() . '/web/' . 'files/zipAsrFiles/srt';
        // if($zip->open($this->srtDown, ZIPARCHIVE::CREATE) !== true) {
        //     return false;
        // }
     
        // if(file_exists($path)){
        //     $zip->addFile($path,basename($path));
        // }
        // $zip->close();
        // $response = new Response(file_get_contents($this->srtDown));
        // $response->headers->set('Content-Type', 'application/zip');
        // $response->headers->set('Content-Disposition', 'attachment;filename="' . $this->srtDown . '"');
        // $response->headers->set('Content-length', filesize($this->srtDown));
        // @unlink($path);
    }
/*
     * 文件夹打包
     * */
    public static function addFileToZip($path,$zip)
    {
        $handler = opendir($path); //打开当前文件夹由$path指定。
        while (($filename = readdir($handler)) !== false) {
            if ($filename != "." && $filename != "..") {
                //文件夹文件名字为'.'和‘..',不要对他们进行操作
                if (is_dir($path . "/" . $filename)) {// 如果读取的某个对象是文件夹,则递归
                    self::addFileToZip($path . "/" . $filename, $zip);
                } else { //将文件加入zip对象
                    // $zip->addFile($path . "/" . $filename);
                    $zip->addFile($path . "/" . $filename,'/srt/'.$filename);
                }
            }
        }
    }
    /*
     * 文件夹打包,直接调用这个就行了
     * param array $paths 需要打包的目录绝对路径,一维数组传多个目录,比如['/imgs/test1/','/imgs/test2','...']
     * param $filename 保存的绝对路径文件名称。比如/data/tmp/test.zip
     * */
    public function dirToZip($paths,$filename)
    {
        $zip = new \ZipArchive();
        try {
            if ($zip->open($filename, $zip::CREATE) == TRUE) {
                foreach ($paths as $path){
                    self::addFileToZip($path, $zip); //调用方法,对要打包的根目录进行操作,并将ZipArchive的对象传递给方法
                }
                $zip->close(); //关闭处理的zip文件
            }
            if(file_exists($filename)){
                return ['code'=>200,'url'=>$filename,'msg'=>'success'];
            }
            return ['code'=>-2002,'msg'=>'打包失败'];
        } catch (\Exception $e) {
            return ['code'=>-2001,'msg'=>$e->getMessage()];
        }
    }

    /*
     * 删除文件夹以及文件夹下的内容
     * $path 传过来的文件路径
     * */
    public function deleteDirectory($path){
        $files = array_diff(scandir($path), array('.', '..'));
        foreach ($files as $file) {
            // 如果是文件,则使用unlink()函数删除
            if (is_file($path.'/'.$file)) {
                unlink($path.'/'.$file);
            }
            // 如果是文件夹,则递归调用rmdir()函数删除
            else {
                rmdir($path.'/'.$file);
            }
        }
        rmdir($path);
    }


    protected function processSpecialChars($questionText)
    {
        return str_replace('&', '&', $questionText);
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

付煜晨

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值