Laravel中ZipArchive::addFile报错:文件或目录不存在求助
解决ZipArchive::addFile()文件不存在错误的方案
你的代码存在几个关键问题,导致出现No such file or directory错误,以下是针对性的修复步骤:
1. 修复变量名错误
方法参数定义的是$solicitations,但查询附件时误用了$solicitation->id(少了末尾的s),这会导致无法正确获取关联的附件数据,修正为:
$anex = AnennexSolicitation::where('id_solicitation', $solicitations->id)->get();
2. 修正Zip文件的打开路径
$zip->open()的参数应该是完整的zip文件路径,而不是目录路径。原代码中$public_dir是目录,需要拼接zip文件名,同时确保目录存在:
$public_dir = public_path() . "/storage/download"; // 目录不存在则创建,赋予读写权限 if (!file_exists($public_dir)) { mkdir($public_dir, 0755, true); } $zip_path = $public_dir . '/' . $zip_name; if ($zip->open($zip_path, ZipArchive::CREATE) === true) { // 后续压缩逻辑 }
3. 修正addFile的参数问题
- 第二个参数不能写死为
.zip,这会导致所有附件被重命名为.zip且互相覆盖,应该保留原文件的文件名,用basename($file_path)获取。 - 确认数据库中存储的
path是完整路径,若为相对路径,需要拼接成服务器可识别的完整路径(比如Laravel中存储到public/storage下的文件,需要用public_path('storage/' . $item->path)拼接)。 - 增加文件存在判断,避免因文件缺失触发错误:
foreach ($anex as $key => $item) { $file_path = public_path('storage/' . $item->path); // 根据实际存储路径调整 if (file_exists($file_path)) { $zip->addFile($file_path, basename($file_path)); } }
4. 修正下载路径
返回下载响应时,要指向正确的zip文件路径,而不是根目录下的annex.zip,还可设置下载后自动删除临时zip文件:
return response()->download($zip_path)->deleteFileAfterSend(true);
完整修正后的代码
public function downloadZipFile(Solicitations $solicitations) { $anex = AnennexSolicitation::where('id_solicitation', $solicitations->id)->get(); $zip_name = 'annex.zip'; $zip = new ZipArchive; $public_dir = public_path() . "/storage/download"; // 确保目录存在 if (!file_exists($public_dir)) { mkdir($public_dir, 0755, true); } $zip_path = $public_dir . '/' . $zip_name; if ($zip->open($zip_path, ZipArchive::CREATE) === true) { foreach ($anex as $key => $item) { $file_path = public_path('storage/' . $item->path); if (file_exists($file_path)) { $zip->addFile($file_path, basename($file_path)); } } $zip->close(); } return response()->download($zip_path)->deleteFileAfterSend(true); }
内容的提问来源于stack exchange,提问作者Soulit
相关产品推荐
相关产品推荐

