从mysql blob数据库向ZipArchive添加图像

时间:2013-06-13 07:08:47

标签: php mysql ziparchive

我最近发现了ZipArchive for PHP,我没有问题从字符串添加文件或文件但是我在MySQL数据库中有一个图像blob,我想添加到ZipArchive。我可以将图像放在一个单独的文件中,我也可以将它作为jpg下载。我希望能够将图像添加到存档中。

以下代码显示了我如何访问我的BLOB

header('Content-Type: image/jpg; charset=utf-8');


// create a file pointer connected to the output stream
$output = fopen('php://output', 'w');

$conB = mysql_connect("localhost", "user_name", "user_pass");//connect to the database
if (!$conB)
    {
        die('Could not connect: ' . mysql_error()); // if cannot connect then send error message
    }
mysql_select_db("binary", $conB); // define database name

$id = $_GET['ids'];

$query = mysql_query("SELECT * FROM tbl_images WHERE ID ='".$id."' ");   



while($row = mysql_fetch_array($query))
    {
        $content = $row['image'];

        header('Content-Disposition: attachment; filename=image"'.$row['ID'].'".jpg');

        fwrite($output, $content);
    }

对我来说一切正常,下面的代码显示了我如何将文件添加到zip存档

$zip = new ZipArchive();
$ZipFileName = "newZipFile.zip";

if ($zip->open($ZipFileName, ZIPARCHIVE::CREATE | ZIPARCHIVE::OVERWRITE) !== true)
    {
        echo "Cannot Open for writing";
    }


$zip->addEmptyDir('newFolder');

$zip->addFromString('text.txt', 'text file');

$zip->close();

//then send the headers to foce download the zip file

header("Content-type: application/zip"); 
header("Content-Disposition: attachment; filename=$ZipFileName"); 
header("Pragma: no-cache"); 
header("Expires: 0"); 

readfile($ZipFileName);

有没有人知道如何一起实施它们?

如果您需要更多信息,我可以提供:)

1 个答案:

答案 0 :(得分:2)

您可以创建ZipArchive,然后使用addFromString()方法从循环中添加图像。我使用下面两个源代码中的代码段。出于简化的原因,省略了数据库连接逻辑。

$zip = new ZipArchive();
$ZipFileName = "newZipFile.zip";

if ($zip->open($ZipFileName, ZIPARCHIVE::CREATE | ZIPARCHIVE::OVERWRITE) !== true)
{
    echo "Cannot Open for writing";
}


$zip->addEmptyDir('newFolder');

$query = mysql_query("SELECT * FROM tbl_images WHERE ID ='".$id."' ");   

while($row = mysql_fetch_array($query))
{
    $zip->addFromString( $row['image_name'],  $row['image']);
}

$zip->close();