我正在尝试从MySQL数据库中获取doc,pdf,docx文件并将所有文档文件压缩在一起。我面临的问题是,我只能下载一个文件而无法将任何文件压缩为ZIP。请帮助我这方面。
<?php
if(isset($_GET['id']) && isset($_REQUEST['clickit']))
{
$id = intval($_GET['id']);
if($id <= 0){
die('The ID is invalid!');
}else{
$username = "";
$password = "";
$servername = "";
$dbname = "";
$conn = new mysqli($servername, $username, $password,$dbname);
if (!$conn){
die("Connection failed: " . mysqli_connect_error());
}
此处我已采取表格中的所有列&t; tbl_uploads_1&#39;并将其传递给结果。
$sql = "SELECT * FROM tbl_uploads_1 ";
$result = $conn->query($sql);
$files = array();
这里我从名为&#39; file_name&#39;的列中获取记录。来自数据库中的表格,其中存储的文件名类似于&#39; abc.doc&#39;。我不确定下面的代码是否是区分具有不同扩展名的文档的正确流程。
while($row = $result->fetch_assoc()) {
$filename = $row["file_name"];
$ext1 = end((explode(".", $filename)));
if($ext1 == pdf){
$files[] = "$filename.pdf";
} else if($ext1 == docx){
$files[] = "$filename.docx";
} else if($ext1 == doc){
$files[] = "$filename.doc";
}
//if ( file_put_contents("$filename.pdf", $content) === FALSE ) {
//echo "Could not write PDF File";
//}
}
这是代码的压缩部分。请查看此内容。
$zipfilename = 'temp_' . time() . '.zip';
$zip->open($zipfilename, ZipArchive::CREATE);
foreach ($files as $file){
$zip->addFile($file);
}
$zip->close();
在我们压缩之前,我应该为每个文件包含头文件方法吗?
header('Content-Type: application/zip');
header('Content-disposition: attachment; filename=filename.zip');
header('Content-Length: ' . filesize($zipfilename));
readfile($zipfilename);
}
//else{
//echo "Err!!";
//}
$conn->close();
}
exit();
?>
答案 0 :(得分:0)
尝试使用此代码从数据库下载文件
$sql = "SELECT * FROM table_name";
if ($result=mysqli_query($conn,$sql))
{
// $rowcount=mysqli_num_rows($result);
// printf("Result set has %d rows.\n",$rowcount);
//define array for storing files
$file = array();
while ($row = mysqli_fetch_assoc($result)) {
//give file name with extension
$name = $_SERVER['DOCUMENT_ROOT']."/demo/mysql_blob/files/".$row['file_name'];
//store file name in array
$file[] = $name;
// store file in one folder named 'files'
file_put_contents($name,$row["fileData"]);
}
$zipname = 'file.zip';
$zip = new ZipArchive;
//open zip file and put all files in zip
foreach ($file as $f) {
if($zip->open($zipname, ZipArchive::CREATE) === TRUE) {
$new_filename = substr($f,strrpos($f,'/') + 1);
$zip->addFile($f,$new_filename);
echo "ok";
} else {
echo "fail";
}
}
if ($zip->close() === false) {
exit("Error creating ZIP file");
}
//check zip file create or not and download it
if (file_exists($zipname)) {
header('Content-Description: File Transfer');
header('Content-Type: application/zip');
header('Content-Disposition: attachment; filename='.basename($zipname));
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Pragma: public');
header('Content-Length: ' . filesize($zipname));
ob_clean();
flush();
readfile($zipname);
exit;
} else {
exit("Could not find Zip file to download");
}
mysqli_free_result($result);
mysqli_close($conn);
}