批量打包下载时,出现文件不存在

想用ZipArchive实现批量打包下载, 运行测试代码如下:

public function download()
    {
        $zip_file = "files.zip"; // 要下载的压缩包的名称

        $files = array([
            'name'=>'develop',
            'path'  => '/file/kI9iQYZElfSBDwxGAH5ARQV2Fu89pzPkyIkrqROc.docx'
        ]);

        if(!file_exists($zip_file)) {
            // 初始化 PHP 类
            $zip = new \ZipArchive();
            $zip->open($zip_file, \ZipArchive::CREATE | \ZipArchive::OVERWRITE);

            foreach ($files as $file) {
                $old_path = $file['path'];
                $new_path = str_replace('/', '\\', $old_path);
                // 所以,它将在 ZIP 中创建另一个名为 "storage/" 的路径,并把文件放入目录。
                $zip->addFile(public_path($new_path), $file['name'] . $extension);
            }

            $zip->close();

            // 我们将会在文件下载后立刻把文件返回原样
            $down_files =  response()->download($zip_file,"test.zip");
        }
        // return $down_files;
        dd('done');
    }

版本信息:laravel 7.x / php 7.3.4nts

最终结果 The file "files.zip" does not exist, 此类程序以前没写过, 实在找不出原因,帮我看一下,是不是哪里出问题了,万分感谢!

《L03 构架 API 服务器》
你将学到如 RESTFul 设计风格、PostMan 的使用、OAuth 流程,JWT 概念及使用 和 API 开发相关的进阶知识。
《L02 从零构建论坛系统》
以构建论坛项目 LaraBBS 为线索,展开对 Laravel 框架的全面学习。应用程序架构思路贴近 Laravel 框架的设计哲学。
讨论数量: 1

提示文件不存在,先确认文件路径是否正确 . 附上test code

        $zip = new \ZipArchive();
        $res = $zip->open($zipFile, \ZipArchive::CREATE | \ZipArchive::OVERWRITE);
        if ($res === TRUE) {
            foreach ($path as $file) {
                $newFilename = substr($file, strrpos($file, '/') + 1);
                $zip->addFile($file, $newFilename);
            }
            $zip->close();
            //下载
            header("Content-Type: application/zip");
            header("Content-Transfer-Encoding: Binary");

            header("Content-Length: " . filesize($zipFile));
            header("Content-Disposition: attachment; filename=\"" . basename($zipFile) . "\"");

            readfile($zipFile);
            //删除文件  压缩包
            foreach ($path as $file) {
                unlink($file);
            }
            unlink($zipFile);
            exit();
        }
3年前 评论

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!