我有这段代码,但它只压缩文件,是否可能将所有目录和其中的文件也包含在内呢?压缩文件应该匹配包含以下内容的文件夹结构:(就像在您的PC上压缩文件夹的常规操作一样)
如果它可以达到结果,另一种代码也是可以接受的。
- Documents
-- test.pdf
-- file.pdf
- Images
-- test.png
- mainfile.xsl
以下是代码:(摘自不同的堆栈解决方案)
// Create a list of files that should be added to the archive.
$files = glob(storage_path("app/course/*.*"));
// Define the name of the archive and create a new ZipArchive instance.
$archiveFile = storage_path("app/course/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());
}
如果它可以达到结果,另一种代码也是可以接受的。