[英]Zip Folder and Download it in Joomla Backend
我正在尝试将自定义 Joomla 3.9 组件中的选项添加到 zip 一些 pdf 并从后端下载它们。 我使用了本教程。 我在 /administrator/components/com_mycomponent/views/item/tmpl/ 中编辑了文件 defalt.php 并添加了以下内容:
<?php
if(isset($_POST['create'])){
$zip = new ZipArchive();
$filename = JPATH_ROOT . '/myfolder/myzipfile.zip';
if ($zip->open($filename, ZipArchive::CREATE)!==TRUE) {
exit("cannot open <$filename>\n");
}
$dir = JPATH_ROOT . '/myfolder/';
// Create zip
createZip($zip,$dir);
$zip->close();
}
// Create zip
function createZip($zip,$dir){
if (is_dir($dir)){
if ($dh = opendir($dir)){
while (($file = readdir($dh)) !== false){
// If file
if (is_file($dir.$file)) {
if($file != '' && $file != '.' && $file != '..'){
$zip->addFile($dir.$file);
}
}else{
// If directory
if(is_dir($dir.$file) ){
if($file != '' && $file != '.' && $file != '..'){
// Add empty directory
$zip->addEmptyDir($dir.$file);
$folder = $dir.$file.'/';
// Read data of the folder
createZip($zip,$folder);
}
}
}
}
closedir($dh);
}
}
}
//Download Created Zip file
if(isset($_POST['download'])){
$filename = JPATH_ROOT . '/myfolder/myzipfile.zip';
if (file_exists($filename)) {
header('Content-Type: application/zip');
header('Content-Disposition: attachment; filename="'.basename($filename).'"');
header('Content-Length: ' . filesize($filename));
flush();
readfile($filename);
// delete file
unlink($filename);
}
}
?>
zip 文件在正确的位置以正确/预期的大小创建,但它已损坏或为空。
我尝试了在其他帖子中找到的解决方案,但没有任何效果。
更新:我用 7-zip 打开压缩文件,发现它包含安装 xampp 的驱动器号。 myzipfile.zip 和所有压缩文件位于:G:/xampp/localhost/myjoomlasite/myfolder
单击 myzipfile.zip 使我像循环一样进入相同的路径。 将 JPATH_ROOT 替换为 JPATH_SITE 给出了相同的结果。
我希望有人能阐明这里发生的事情。
使用$zip->addFile($filename)
您正在将具有完整路径的文件添加到 zip 存档。 我想拥有相对路径是你的目标? 因此,您需要剪切路径并使用$zip->addFile($filename, $localFileName)
。 可能有更好的解决方案,最简单的方法是简单地从$filename
中删除基本路径以获取$localFileName
。
您还可以使用RecursiveDirectoryIterator
循环浏览您的文件和目录。
也许这个链接也有帮助如何[递归地] Zip PHP 中的目录?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.