dongyu1918
dongyu1918
2014-09-14 05:16

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

  • loops
  • file
  • php
  • zip
  • download
已采纳

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 douniao7308 7年前

    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);
    
    点赞 评论 复制链接分享

为你推荐