php – 如何在laravel 5中压缩文件夹?
作者:互联网
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文件,我无法下载它.请需要一些帮助
解决方法:
首先:if条件下的相同比较会触发我.
许多人可能不知道这一点,但ZipArchive::addFile()
和ZipArchive::close()
也返回布尔值以显示他们的成功(或失败).您应该始终检查它们,因为如果文件夹不可写,则只返回close方法.
然后你说如果你调用控制器动作就没有下载.那就对了.您没有告诉程序将某些内容流式传输到客户端.你只需设置两个变量,一个用于标题?另一个用于上面用于打开zip文件的完全相同的文件路径.
以下代码是一个工作示例(至少在具有正确文件夹权限的已配置环境中)此过程如何工作并为您的任务获得一些“灵感”.
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());
}
});
标签:ziparchive,php,laravel 来源: https://codeday.me/bug/20190828/1751082.html