nee*_*elp 5 php ziparchive laravel
需要一些 Laravel zip 文件的帮助。我在公共文件夹中有一个文件夹,我想在用户单击按钮时创建该文件夹的 zip(temp_file 文件夹)。
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;
}
Run Code Online (Sandbox Code Playgroud)
但它似乎没有创建 zip 文件,我无法下载它。请需要一些帮助
很多人可能不知道这一点,但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)) {
throw new Exception("Zip file could not be created: ".$archive->getStatusString());
}
// Loop through all the files and add them to the archive.
foreach ($files as $file) {
if (! $archive->addFile($file, basename($file))) {
throw new Exception("File [`{$file}`] could not be added to the zip file: ".$archive->getStatusString());
}
}
// Close the archive.
if (! $archive->close()) {
throw new Exception("Could not close zip file: ".$archive->getStatusString());
}
// Archive is now downloadable ...
return response()->download($archiveFile, basename($archiveFile))->deleteFileAfterSend(true);
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
13758 次 |
最近记录: |