dongyu1918 2014-09-14 05:16
浏览 29
已采纳

使用.zip存档将文件作为附件下载

I am having this function in my class name MyMethods:

function zipDownload($file_names,$file_path){
    $zip_file_name = date('Y-m-d-h-i-s').'_attachement.zip';
    $zip = new ZipArchive();
    if($zip->open($zip_file_name, ZIPARCHIVE::CREATE )!==TRUE) {
        echo("cannot open <".$zip_file_name.">
");     
        }
    else{
        $filePathAry = explode("/",$file_path);
        $count = count($filePathAry);
        $path = '';
        for($i=0; $i<=$count - 2; $i++){
            $path .= $filePathAry[$i].'/';
            }
        $path = $this->baseDir().$path;
        foreach($file_names as $files){
            $zip->addFile($path,$files);
            }
        $zip->close();      
        header("Content-type: application/zip"); 
        header("Content-Disposition: attachment; filename=".$zip_file_name); 
        header("Pragma: no-cache"); 
        header("Expires: 0"); 
        readfile($zip_file_name);
        exit;   
        }   
    }

I am calling this by the following code from presentation layer:

//filled array with names of files:
loop over files name{
         $filesAry[] = $fileName;
         }
$method->zipDownload($filesAry,$zipPath);

on debugging i get this link as an individual file path:

 Path : http://localhost/sites/mySite/bdc/uploader/exhibitsFiles/06_08_2014
 File Name: xyb.jpg

after clicking on the download all file as attachment, it produces .zip file but it does not open as normal .zip file?

What i am missing? please help me in this. thanks.

  • 写回答

1条回答 默认 最新

  • douniao7308 2014-09-14 06:06
    关注

    Use a filesystem path rather than an http url in $zip->addFile() and make sure the file you're adding exists and is readable.

    If you must grab the file to be added to the archive over http, use something along the lines of:

    $zip->addFromString($files, file_get_contents($path));
    

    in place of:

    $zip->addFile($path,$files);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 stm32流水灯+呼吸灯+外部中断按键
  • ¥15 将二维数组,按照假设的规定,如0/1/0 == "4",把对应列位置写成一个字符并打印输出该字符
  • ¥15 NX MCD仿真与博途通讯不了啥情况
  • ¥15 win11家庭中文版安装docker遇到Hyper-V启用失败解决办法整理
  • ¥15 gradio的web端页面格式不对的问题
  • ¥15 求大家看看Nonce如何配置
  • ¥15 Matlab怎么求解含参的二重积分?
  • ¥15 苹果手机突然连不上wifi了?
  • ¥15 cgictest.cgi文件无法访问
  • ¥20 删除和修改功能无法调用