php - 将图像从 mysql blob 数据库添加到 ZipArchive

标签 php mysql ziparchive

我最近发现了 PHP 的 ZipArchive,添加文件或从字符串中添加文件没有问题,但是我在 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);

有人知道我如何将它们一起实现吗?

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

最佳答案

您可以创建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();

关于php - 将图像从 mysql blob 数据库添加到 ZipArchive,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17081194/

相关文章:

php - 用 PHP 实现的 IMAP 或 POP3 服务器

mysql - 使用 union 在 mysql 表中进行多个连接

mysql - 使用 CodeIgniter 传递运行总计查询

php - ZipArchives 存储绝对路径

ios - 无法编译 Ziparchive 库 (iOS)

javascript - 如何动态更改位置并记录该位置 javascript PHP

php - 不在字符串中的 `${...}` 在 PHP 中意味着什么?

javascript - 如何使大文本字段的文本框变宽

mysql - w3wp.exe 使 IIS 8.5 经典 ASP 页面崩溃

php - 从 zip 文件夹中提取文件