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

时间:2017-08-02 01:50:34

标签: php laravel ziparchive

需要一些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文件,我无法下载它。请需要一些帮助

3 个答案:

答案 0 :(得分:5)

首先:if条件中的相同比较会触发我。

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

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

以下代码是一个正在运行的示例(至少在具有正确文件夹权限的已配置环境中)此过程 如何工作并为您提供一些灵感" #34;为了你的任务。

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());
    }
});

答案 1 :(得分:0)

你必须用波普尔格式 这样做

$File = 'path-ZipFile/fileName' . time() . '.zip';
$zip = new \ZipArchive();
$res = $zip->open($File, \ZipArchive::CREATE);

if ($res === TRUE) {
    $zip->addFile("fullpath/filename.extinction");
    $zip->close();
}

header("Content-Type: application/zip");
header("Content-Disposition: attachment; filename=\"" . basename($File) . "\"");
header("Content-Length: " . filesize($File));
header("Pragma: no-cache");
header("Expires: 0");
readfile($File);
header("Connection: close");

答案 2 :(得分:0)

如果一切都适合您,您需要检查public_path()每个目录权限。 该目录必须具有 0755 0777 权限才能创建和执行文件。 请先检查您的目录权限。

相关问题