【发布时间】:2014-01-01 16:29:57
【问题描述】:
我有一个 php 文件,它将图像存储在数据库中的 BLOB 中。上传部分工作正常。但是它不会显示图像,我不知道为什么。帮助表示赞赏。
两个文件:
index.php
<!DOCTYPE HTML>
<html>
<head>
<title>Upload Image</title>
</head>
<body>
<h1>Upload an Image</h1>
<form action="index.php" method="POST" enctype="multipart/form-data">
<label for="image">File:</label>
<input type="file" name="image">
<input type="submit" value="Upload">
</form>
<?php
//connect
mysql_connect("localhost", "root","") or die(mysql_error());
mysql_select_db("up") or die(mysql_error());
//file stuff
$file= $_FILES['image']['tmp_name'];
if(!isset($file))
echo "Please select an image";
else {
$image=mysql_real_escape_string(file_get_contents($_FILES['image']['tmp_name']));
$imageName=mysql_real_escape_string($_FILES['image']['name']);
$imageSize=getimagesize($_FILES['image']['tmp_name']);
if(!$imageSize)
echo "Thats not an image";
else {
//upload
$query="INSERT INTO store VALUES('','$imageName','$image')";
$sendQuery=mysql_query($query);
if(!$sendQuery)
echo "This is embarressing. It didn't work";
else {
$lastid=mysql_insert_id();
echo "Image was uploaded. <br>Your image:";
echo "<img src=get.php?id=$lastid/>";
}
}
}
?>
</body>
</html>
和get.php:
<?php
//connect
mysql_connect("localhost", "root","") or die(mysql_error());
mysql_select_db("up") or die(mysql_error());
$id=mysql_real_escape_string($_REQUEST(['id']));
$imageQuery="SELECT * FROM store WHERE id=$id;";
$sendImageQuery=mysql_query($imageQuery);
$image=mysql_fetch_assoc($sendImageQuery);
$image=$image['image'];
header("Content-type: image/jpeg");
echo $image;
?>
【问题讨论】:
-
您将图像存储在数据库中是否有任何特殊原因?一般只有图像的位置存储在db中
-
你想如何显示图像?我假设您正在这样做:
<img src="get.php?id=2"/>,是吗?如果您将该 URL 直接放入浏览器,您会看到什么? -
store表的架构是什么样的?我不确定你是否真的正确插入它。我假设第一列是一个 AUTO_INCREMENT 字段,如果是这样,它应该是INSERT INTO store VALUES(NULL,'$imageName','$image') -
@Fred - 怎么样?最后一个 id 仅适用于特定用户运行的最后一个查询。
-
@Fred-ii-:来自 MySQL 的文档 (dev.mysql.com/doc/refman/5.0/en/mysql-insert-id.html):
The value of mysql_insert_id() is affected only by statements issued within the current client connection. It is not affected by statements issued by other clients.。因此,使用mysql_insert_id没有没有 问题。多人同时上传不会破坏这个:-)