如何创建Zip文件和下载CakePHP中?(How to create Zip file and d

2019-10-19 05:13发布

我试图创建使用CakePHP 1.3 zip文件。 该文件描述存储在数据库中。 在我的控制,我使用下面的逻辑。

   // Fetching File description form database.     
   $this->view = 'Media';
   $user_id=$this->Session->read('userData.User.id');
   $condition = "Document.isdeleted = '0' AND Document.project_id='".  $project_id."'";
   $projectDocumentList = $this->Document->find("all",array('conditions'=>$condition,'fields'=>array('Document.id','Document.document_name','Document.path'),'order' => array('Document.id ASC')));
   $this->set('projectDocumentList',$projectDocumentList);
   if(!empty($projectDocumentList)){
   $fileNames = "";
   $fileNamesArr = array();
    foreach($projectDocumentList as $projectDocument){     
     $fileNamesArr[ ]= $projectDocument['Document']['document_name'];
    }
   }

   // Making zip
   $archive_file_name='myFile.zip';
   $file_path= "my_file_path";// Here I'm using my server basepath

   $zip = new ZipArchive();   
   if ($zip->open($archive_file_name, ZIPARCHIVE::CREATE )!==TRUE) {
    exit("cannot open <$archive_file_name>\n");
   }

   foreach($fileNamesArr as $files)
   {
   $zip->addFile($file_path.$files,$files);
   //echo $file_path.$files."<br>"; // This can show the file in browser
   }

   $zip->close();
   header("Content-type: application/zip");
   header("Content-Disposition: attachment; filename=$archive_file_name");
   header("Pragma: no-cache");
   header("Expires: 0");
   readfile("$archive_file_name");
   exit;

现在下载的ZIP文件作为myFile.zip,但是当我要打开该文件,它抛出一个错误“的档案或者是在未知的格式或损坏”。

Answer 1:

创建整个文件夹的Zip文件

// Get real path for our folder
$rootPath = realpath('folder-to-zip');

// Initialize archive object
$zip = new ZipArchive();
$zip->open('file.zip', ZipArchive::CREATE | ZipArchive::OVERWRITE);

// Create recursive directory iterator
/** @var SplFileInfo[] $files */
$files = new RecursiveIteratorIterator(
    new RecursiveDirectoryIterator($rootPath),
    RecursiveIteratorIterator::LEAVES_ONLY
);

foreach ($files as $name => $file)
{
    // Skip directories (they would be added automatically)
    if (!$file->isDir())
    {
        // Get real and relative path for current file
        $filePath = $file->getRealPath();
        $relativePath = substr($filePath, strlen($rootPath) + 1);

        // Add current file to archive
        $zip->addFile($filePath, $relativePath);
    }
}

// Zip archive will be created only after closing object
$zip->close();

而不是通过压缩文件到视图的路径。

$this->set('Zip_path'.zip_file_name);


文章来源: How to create Zip file and download in CakePhp?