2014-01-13 63 views
1

我試圖使用CakePhp 1.3創建zip文件。文件描述存儲在數據庫中。在我的控制器中,我使用以下邏輯。如何創建zip文件並在cakephp中下載

// 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,但是當我要打開該文件,它拋出一個錯誤「的檔案或者是在未知的格式或損壞」。 任何幫助將不勝感激。

感謝

+0

'$ archive_file_name'不應該只是文件名,而應該是完整的文件相對路徑。 – Rikesh

回答

1

創建整個文件夾

// 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(); 

而不是通過壓縮文件的視圖路徑的ZIP文件。

$this->set('Zip_path'.zip_file_name); 
相關問題