php - 将 blob 图像(存储在数据库中)下载到我的计算机

标签 php mysql image mysqli blob

我有存储在数据库中的 blob 图像,我想将其下载到我的设备。

  • 图像将被下载(如 ***.jpg),但已损坏。 这是我的 download.php 代码

    <?php
    $servername = "localhost";
    $dbusername = "root";
    $dbpassword = "";
    $dbname = "text_blob1";
    $con= new mysqli($servername, $dbusername, $dbpassword, $dbname); 
    
    $id=$_GET["id"];
    $sql = "select * from table1 where id=$id "; // 1
    $res = $con->query($sql);
    while($row = $res->fetch_assoc())
     { 
     $name = $row['name'];
      echo "<br>";
     $size =  $row['size'];
      echo "<br>";
     $type = $row['extension'];
      echo "<br>";
     $image = $row['image'];
     }
    
      header("Content-type: ".$type);
      header('Content-Disposition: attachment; filename="'.$name.'"');
      header("Content-Transfer-Encoding: binary"); 
      header('Expires: 0');
      header('Pragma: no-cache');
      header("Content-Length: ".$size);
    
      echo $image;
      exit($image);   
       ?>
    

谢谢<3

最佳答案

输出到页面的所有内容都被视为文件内容。我想你不想要"<br>"位于您的文件内容中。

第二点 - 在设置 header 之前不要执行任何输出。

第三点 - exit('string')输出'string' ,因此您将文件内容输出两次:使用 echo并与 exit .

因此,您的代码应如下所示:

$id=$_GET["id"];
$sql = "select * from table1 where id=$id "; // 1
$res = $con->query($sql);
while($row = $res->fetch_assoc())
{ 
    $name = $row['name'];
    $size =  $row['size'];
    $type = $row['extension'];
    $image = $row['image'];
}

header("Content-type: ".$type);
header('Content-Disposition: attachment; filename="'.$name.'"');
header("Content-Transfer-Encoding: binary"); 
header('Expires: 0');
header('Pragma: no-cache');
header("Content-Length: ".$size);

echo $image;
exit();

关于php - 将 blob 图像(存储在数据库中)下载到我的计算机,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43009763/

相关文章:

CSS:图像 100% 高度 - 50px

php - 使用 onkeyup JS 事件检查输入的值是否唯一

javascript - Cycle2 未运行

php - mysql,根据类别的UUID获取产品的总重量

mysql - 了解 postgresql/sql 的细节

javascript - 删除从输入 js 创建的缩略图

php - 每 5 秒用 jQuery/Ajax 刷新一个表

php - Hiphop for PHP 等工具如何处理异构数组?

MySQL 在每个组中选择第一个、第二个和最后一个值的最佳方法

c# - 使用 C# 缩小 Jpeg 图像的效果不佳