【发布时间】:2017-04-05 00:24:16
【问题描述】:
所以我一直在尝试从我的 WAMP 服务器创建和下载一个 .zip 文件,以便在我正在处理的私有开发服务器上使用,并且在尝试下载我的 .zip 文件时似乎遇到了一些重大问题已经创造出来了。
代码似乎按预期工作。它查看包含我要下载的文件的文件夹,并将它们添加到我的拉链类使用的数组中(靠近底部的函数调用)。
当我运行此代码时,会在服务器上创建 .zip 文件;我可以看到它在那里,打开它,看到文件已添加到 .zip 中。我也可以将压缩文件夹从我的本地 wamp 服务器中拖出来,然后从我的客户端机器中提取出来。 问题是当我尝试下载压缩文件时。它似乎下载了文件,但是当我打开它时,会出现一个 Windows 框,上面写着“Windows 无法打开文件夹,压缩(压缩)文件夹 /path&name/ 无效”,但它在服务器端运行良好。
我也尝试使用此方案来下载和查看单个文件(非压缩文件),它们总是以随机文本的形式出现,这让我相信它与从服务器向服务器提供下载有关客户端机器。
我也尝试在我的实时服务器上运行此代码。尝试查看时也会发生同样的事情,除了(在 chrome 中)一条消息说“/filename/ 不经常下载并且可能很危险”。
我已经检查了 stackoverflow 上的各种帖子以获取解决方案,但似乎没有帮助。
<?php
require_once 'zipper.php';
$dir_path = "files/";
$arrFiles = array(); //Array Of files to be compressed into zip
if(is_dir($dir_path)){
$files = scandir($dir_path); //create and array that stores all dir files.directories including '.' and '..'
foreach($files as $newFile){ //Loop through the files
if($newFile != '.' && $newFile != '..'){ //If the current found is NOT . or ..
echo "$newFile<br>";
$newFile = $dir_path . $newFile;
$arrFiles[] = $newFile; //add to the array of files to compress/zip
}
}
}
//print_r($dir_path."name.zip");
$zipper = new Zipper; //create the zipper object (contains functions for preparing the .ZIP)
$zipper->add($arrFiles); //add files to Zipper ZIP array
$filename = "myFile.zip";
$filepath = $dir_path.$filename; //Path to the new .zip with the ZIP name included in the path
echo $filepath;
echo "<br>";
$zipper->store($filepath); //create the ZIP & store for download
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=".basename($filepath).";" );
header("Content-Transfer-Encoding: binary");
header("Content-Length: ".filesize($filepath));
readfile("$filepath");
?>
下面是我使用的“zipper.php”文件。
<?php
class Zipper{
private $_files = array(), $_zip;
public function __construct(){
$this->_zip = new ZipArchive;
}
public function add($input){
if(is_array($input)){
$this->_files = array_merge($this->_files, $input);
}else{
$this->_files[] = $input;
}
}
public function store($location = null){ //used for storing the files added from the directory
if(count($this->_files) && $location){
foreach($this->_files as $index => $file){
if(!file_exists($file)){
unset($this->_files[$index]);
}
elseif(preg_match('/.zip$/', $file)){ //if the file was already compressed once, remove it from the array of files to zip
unset($this->_files[$index]);
}
}
print_r($this->_files);
if($this->_zip->open($location, file_exists($location) ? ZIPARCHIVE::OVERWRITE : ZIPARCHIVE::CREATE)){ //create the .ZIP; if it exists overwrite, else create it
foreach($this->_files as $file){
$this->_zip->addFile($file, $file); //for each file in our array add it to the zip
}
$this->_zip->close(); //close the zip once completed
}
}
}
}
任何帮助将不胜感激。
【问题讨论】: