我想显示图像而不是下载它(数据库blob中的图像)

8

我想显示图片而不是下载它。

我在我的数据库表中有一张图片,列名为BLOB。

这段代码会下载图片,但我想要显示它:

$query = "SELECT * FROM upload";
$result  = mysql_query($query);
$row = mysql_fetch_array($result);
$content =  $row['content'];
$size =  $row['size'];
$type =  $row['type'];
header("Content-length: $size");
header("Content-type: $type");

// The following headers make the image download, but I don't want it to
// download, I want to show the image. What should I do?
// header("Content-Disposition: attachment; filename=$name");

echo $content;

1
您的代码应该可以正常工作,因为您已经注释掉了“Content-Disposition”行。真正重要的是“Content-Type”头部信息。您应该确保它包含类似于“image/jpeg”这样的内容,以便浏览器知道这是一张图片。 - kijin
你清除了浏览器缓存吗?这种情况经常发生在我身上。 - kijin
4个回答

7
attachment 的相反 content-dispositioninline。试试这个:
header("Content-Disposition: inline; filename=$name");

1
如果您想更动态地使用它,请将原始代码制作成脚本,并像这样调用它:
<img src="image.php?imageid=$myImageID" />

而你的脚本是:

$myImageID = $_GET["myImageID"];
$query = "SELECT * FROM upload where id='"+$myImageID+"'";
$result  = mysql_query($query);
$row = mysql_fetch_array($result);
$content =  $row['content'];
$size =  $row['size'];
$type =  $row['type'];
header("Content-length: $size");
header("Content-type: $type");
//header("Content-Disposition: attachment; filename=$name");---> this headers make system to download , but i dont want to download, i want to show image, what  should i do ,
echo $content; ?>"

以上代码片段现在无法正常工作,它只显示路径,而不是图片,例如http://localhost/source/iq/upload-file-mysql.php。 - Bharanikumar
如果你的 PHP 代码不正确,图片将无法显示。如果你在浏览器中访问类似于 image.php?imageId=$myImageID 的 URL,你应该能够看到你的图片。 - CristiC
这段代码非常危险!难道你不知道永远不能信任用户输入吗?这是引发 SQL 注入的绝对途径! - vasilevich

0

你需要确保除了头部和图像内容之外,没有其他东西被发送到客户端。也许你想在 echo $content; 后面加上 exit,但这不是最佳实践,也不能确保在输出图像内容之前没有其他内容被发送,但应该可以完成工作。


-1

您可以使用以下代码显示图像而非下载它:

<a href="myimage.png">Click to download</a>

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接