【问题标题】:Laravel 4 how to zip fileLaravel 4如何压缩文件
【发布时间】:2013-05-31 06:12:05
【问题描述】:

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

我需要压缩文件夹/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 对象无效或未初始化

【问题讨论】:

  • 告诉我们你尝试了什么

标签: php laravel laravel-4


【解决方案1】:

当您以“/”开始路径时,路径变为绝对,这将导致 PHP 从服务器文件系统的根目录查找。而是使用public_path() 获取磁盘上到public 的路径...

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

【讨论】:

    【解决方案2】:

    这是压缩后自动下载 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');
    }
    

    【讨论】:

      猜你喜欢
      • 2018-08-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-09-12
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多