ICode9

精准搜索请尝试: 精确搜索
首页 > 编程语言> 文章详细

php – 如何在laravel 5中压缩文件夹?

2019-08-28 11:29:49  阅读:254  来源: 互联网

标签:ziparchive php laravel


laravel zip文件需要一些帮助.我在公共文件夹中有一个文件夹,我想在用户单击按钮时创建该文件夹(temp_file文件夹)的zip.

public function testing()
{
    $public_dir = public_path('temp_file/');
    $zipFileName = 'myZip.zip';
    $zip = new ZipArchive;

    if ($zip->open($public_dir . '/' . $zipFileName, ZipArchive::CREATE) === TRUE) {
        $zip->addFile('file_path', 'file_name');
        $zip->close();
    }

    $headers = array('Content-Type' => 'application/octet-stream');

    $filetopath = $public_dir . '/' . $zipFileName; 
}

但它似乎没有创建zip文件,我无法下载它.请需要一些帮助

解决方法:

首先:if条件下的相同比较会触发我.

许多人可能不知道这一点,但ZipArchive::addFile()ZipArchive::close()也返回布尔值以显示他们的成功(或失败).您应该始终检查它们,因为如果文件夹不可写,则只返回close方法.

然后你说如果你调用控制器动作就没有下载.那就对了.您没有告诉程序将某些内容流式传输到客户端.你只需设置两个变量,一个用于标题?另一个用于上面用于打开zip文件的完全相同的文件路径.

以下代码是一个工作示例(至少在具有正确文件夹权限的已配置环境中)此过程如何工作并为您的任务获得一些“灵感”.

public function testing() {
    // create a list of files that should be added to the archive.
    $files = glob(storage_path("app/images/*.jpg"));

    // define the name of the archive and create a new ZipArchive instance.
    $archiveFile = storage_path("app/downloads/files.zip");
    $archive = new ZipArchive();

    // check if the archive could be created.
    if ($archive->open($archiveFile, ZipArchive::CREATE | ZipArchive::OVERWRITE)) {
        // loop through all the files and add them to the archive.
        foreach ($files as $file) {
            if ($archive->addFile($file, basename($file))) {
                // do something here if addFile succeeded, otherwise this statement is unnecessary and can be ignored.
                continue;
            } else {
                throw new Exception("file `{$file}` could not be added to the zip file: " . $archive->getStatusString());
            }
        }

        // close the archive.
        if ($archive->close()) {
            // archive is now downloadable ...
            return response()->download($archiveFile, basename($archiveFile))->deleteFileAfterSend(true);
        } else {
            throw new Exception("could not close zip file: " . $archive->getStatusString());
        }
    } else {
      throw new Exception("zip file could not be created: " . $archive->getStatusString());
    }
});

标签:ziparchive,php,laravel
来源: https://codeday.me/bug/20190828/1751082.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有