【问题标题】:Downloading image stored as a BLOB does not work下载存储为 BLOB 的图像不起作用
【发布时间】:2019-12-06 10:13:49
【问题描述】:

我的脚本返回一个具有正确名称但没有任何文件类型或扩展名的文件。当我打开这个文件时,它只显示非常长的几乎无限的字符串。我想返回一个图像(.png 文件)并在

中为其指定了 MIME 类型

header("内容类型:图片/png"); 我的脚本是:

    $query = "SELECT * " ."FROM images WHERE filename = '$name2'";
$result = mysqli_query($connect,$query) 
       or die('Error, query failed');
list($file, $content) = mysqli_fetch_array($result);
header("Content-type: image/png");
header("Content-Disposition: attachment; filename=$file");
ob_clean();
flush();
echo $content;
mysqli_close($connect);
exit;

而回显的文件就是这样的无限字符串:

¸A

它不会将 BLOB 转换为正确的文件类型 (.png)

【问题讨论】:

标签: php database mysqli blob


【解决方案1】:
<?php
$connection =  mysqli_connect("localhost","root"," ",your_database)
           or die('Database Connection Failed');
mysqli_set_charset($connection,'utf-8');

$id = 1;

 // Use a prepared statement in production to avoid SQL injection;
 // we can get away with this here because we're the only ones who
 // are going to use this script.
$query = "SELECT * " ."FROM images WHERE filename = '$name2'";
$result = mysqli_query($connect,$query) 
   or die('Error, query failed');
list($id, $file, $type, $size,$content) = mysqli_fetch_array($result);
header("Content-length: $size");
header("Content-type: $type");
header("Content-Disposition: attachment; filename=$file");
ob_clean();
flush();
echo $content;
mysqli_close($connection);
exit;

?>

对我有用!!

【讨论】:

  • 我不存储尺寸。我应该吗?
  • 关于文件类型的同样问题。我没有将它存储在数据库中,因为我在代码中对其进行了硬编码: header("Content-type: image/png");而不是: header("Content-type: $type");我也应该存储它吗?
猜你喜欢
  • 1970-01-01
  • 2018-11-21
  • 2018-08-03
  • 2011-06-08
  • 1970-01-01
  • 2016-10-11
  • 2017-11-08
  • 2015-03-26
  • 2021-07-25
相关资源
最近更新 更多