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);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度