2016-12-05 37 views
0

我正在尝试将图像添加到zip文件并强制使用标题下载它。下面是我现在使用的代码片段。在使用Php zip下载代码时遇到问题

$zip = new ZipArchive(); 
$zip_name = 'design_images_'.time() .".zip"; 
if($zip->open($zip_name, ZIPARCHIVE::CREATE)!==TRUE){ 
    $error .= "* Sorry ZIP creation failed at this time"; 
} 
    $i = 0; 
foreach($valid_files as $file){ 
    $image_name = 'design_image_' . $i; 
    $zip->addFile($file, $image_name); 
    $i++; 
} 
$zip->close(); 
if(file_exists($zip_name)){ 
    // force to download the zip 
    header("Pragma: public"); 
    header("Expires: 0"); 
    header("Cache-Control: must-revalidate, post-check=0, pre-check=0"); 
    header("Cache-Control: private",false); 
    header('Content-type: application/zip'); 
    header('Content-Disposition: attachment; filename="'.$zip_name.'"'); 
    readfile($zip_name); 

} 

当我尝试打开zip文件时出现错误:归档文件已损坏。

+0

你肯定在'zip-> open'有没有错误? 'readfile'后面有输出吗? –

+0

是的,压缩包以准确的大小成功下载,但无法解压缩。当我双击压缩文件时,我可以看到它里面的所有图像都有适当的尺寸。但同样无法打开或提取任何一个。 –

回答

0

服务尝试下载之前清理输出缓冲:

if(file_exists($zip_name)){ 

    // Clean the output buffer. 
    while (ob_get_level()) { 
    ob_end_clean(); 
    } 

    // force to download the zip 
    header("Pragma: public"); 
    header("Expires: 0"); 
    header("Cache-Control: must-revalidate, post-check=0, pre-check=0"); 
    header("Cache-Control: private",false); 
    header('Content-type: application/zip'); 
    header('Content-Disposition: attachment; filename="'.$zip_name.'"'); 
    readfile($zip_name); 

}