【问题标题】:Download files as attachement with .zip archieve使用 .zip 存档将文件作为附件下载
【发布时间】:2014-09-14 05:16:28
【问题描述】:

我的班级名称 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.">\n");     
        }
    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;   
        }   
    }

我通过表示层的以下代码调用它:

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

在调试时,我将此链接作为单独的文件路径:

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

单击下载所有文件作为附件后,它会生成 .zip 文件,但无法正常打开 .zip 文件?

我错过了什么?请帮助我。谢谢。

【问题讨论】:

    标签: php file loops zip download


    【解决方案1】:

    $zip-&gt;addFile() 中使用文件系统路径而不是http url,并确保您添加的文件存在且可读。

    如果您必须通过 http 获取要添加到存档的文件,请使用以下内容:

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

    代替:

    $zip->addFile($path,$files);
    

    【讨论】:

    • 谢谢您,先生,我更改的代码与旧代码略有不同,但想法与您在解决方案中添加的相同。它为我工作。我已经检查过了。谢谢
    猜你喜欢
    • 1970-01-01
    • 2014-09-19
    • 2010-12-17
    • 1970-01-01
    • 2017-06-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多