Laravel 4如何压缩文件

时间:2013-06-04 18:15:47

标签: php laravel laravel-4

任何正文请建议我如何压缩文件夹并在laravel4上下载该zip文件。

我需要压缩文件夹/public/zipfolder/

压缩后

然后自动下载zipfolder.zip

我安装此软件包

https://github.com/codeless/ziparchiveex

并路由到

public function show($id)
{
    //echo $id;
    # ZipArchive as usual:
    $zip = new ZipArchiveEx();
    //$zip->open('my.zip', ZIPARCHIVE::OVERWRITE);

    # Add whole directory including contents:
    $zip->addDir('/public/zipfolder/');

    # Only add the contents of the directory, but
    # not the directory-entry of "mydir" itself:
    //$zip->addDirContents('mydir');

    # Close archive (as usual):
    $zip->close();
}

我的错误低于

  

ZipArchive::addEmptyDir():无效或已整合的Zip对象

2 个答案:

答案 0 :(得分:1)

使用" /"开始路径时路径变为绝对并将导致PHP从服务器的文件系统的根目录查看。而是使用public_path()将磁盘上的路径设置为public ...

$zip->addDir(public_path().'/zipfolder/');

答案 1 :(得分:-1)

这是代码适用于你的压缩然后自动下载my.zip

public function show($id)
{
    //echo $id;
    # ZipArchive as usual:
    $zip = new ZipArchiveEx();
    $zip->open('my.zip', ZIPARCHIVE::OVERWRITE);

    # Add whole directory including contents:
    $zip->addDir('/public/zipfolder/');

    # Only add the contents of the directory, but
    # not the directory-entry of "mydir" itself:
    //$zip->addDirContents('mydir');

    # Close archive (as usual):
    $zip->close();

    // Stream the file to the client 
    header("Content-Type: application/zip"); 
    header("Content-Length: " . filesize('my.zip')); 
    header("Content-Disposition: attachment; filename=\"my.zip\""); 
    readfile('my.zip'); 

    unlink('my.zip');
}