PHP 无法访问新创建的 zip 文件

问题描述 投票:0回答:1

我使用 Laravel 5.2 和 Zipper 快速创建 ZIP 存档并由用户下载。我认为这个问题一般与 Laravel 或 Zipper 没有严格关系。步骤:

  1. 用户点击链接download_all
  2. 第一个 php 脚本创建存档。
  3. 接下来,相同的脚本推送创建的文件以强制用户下载。

一切听起来都很正常,但我有奇怪的行为,在创建 zip 存档后(第 2 点)php/server 看不到这个新创建的文件。 $filePath 上的 filesize 和 file_exists 都返回 false,但文件存在。 我无法读取文件为什么?

当我将用户重定向到 $filePath (而不是读取它并推送下载)时,一切正常并且用户获取文件。但为什么我无法在“脚本生命周期”期间访问新创建的文件? $paths 是正确的。 在 Windows 7 和 Unix 上测试。

有什么想法吗?

代码:

public function downloadAll($id)
    {
        $sourceFilesDir   = 'upload/source/' . $id;
        $zipPath          = 'upload/source-zip/' . date('Y-m-d-H-i-s') . '.zip';

        Zipper::make($zipPath)->add($sourceFilesDir);

        $fullPath = public_path($zipPath);

        // works
        // return response()->redirectTo($zipPath);

        $headers = [
            'Content-Type: application/zip',
            'Content-Transfer-Encoding: Binary',
            'Content-Length: ' . filesize($fullPath),
        ];

        // dont works, cant see file
        return response()->download($fullPath, basename($zipPath), $headers);
    }
php laravel-5 zip php-ziparchive
1个回答
1
投票

由@Holger 提交。 拉链应关闭以保存文件。

正确代码:

Zipper::make($zipPath)->add($sourceFilesDir)->close();

->关闭()

不幸的是,Zipper 文档中没有明确提及这一点。

© www.soinside.com 2019 - 2024. All rights reserved.