我在上传图片时遇到显示图片的问题。它将所有数据插入到mysql中,但它们不会在localhost上显示为预览图像。它只是显示为一个断开的链接。
以下是我用于使用文件上传将图像插入数据库的代码:
<?php
error_reporting(E_ALL^E_NOTICE);
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd"
>
<html lang="en">
<head>
<title> Member System- Log In</title>
</head>
<body>
<form action="register.php" method="post"
enctype="multipart/form-data">
<label for="file">Filename:</label>
<input type="file" name="image" ><br>
<input type="submit">
</form>
<?php
//connect to database
mysql_connect("localhost", "root", "root") or die("mysql_error()");
mysql_select_db("users") or die("mysql_error()");
//file properties
$file= $_FILES['image']['tmp_name'];
if (!isset($file))
echo "Please select an image";
else {
$image= addslashes(file_get_contents($_FILES['image']['tmp_name']));
$image_name=addslashes($_FILES['image']['name']);
$image_size= getimagesize($_FILES['image']['tmp_name']);
}
if ($image_size==FALSE)
echo "That's not an image.";
else {
if (!$insert= mysql_query("INSERT INTO images VALUES ('$id','$image_name','$image')"))
echo "Problem uploading image.";
else {
$lastid= mysql_insert_id();
// create the query
//$sql = "select image from images where id=1";
// the result of the query
//$result = mysql_query($sql) or die("Invalid query: " .mysql_error());
// there should only be 1 result (if img_id = the primary index)
//$pic = mysql_fetch_array($result);
// show the image
//echo "Image uploaded. <p/> Your image: <p/> <img src='picture/".$pic['img_name']."' width='300' height='300'/>";
echo "Image uploaded. <p/> Your image:<p /><img src=<?php get.php?id=$lastid >";
}
}
?>
Then I called get.php to retrieve the last image id from the database. Here's that code:
<?php
mysql_connect("localhost", "root", "root") or die("mysql_error()");
mysql_select_db("users") or die("mysql_error()");
$id= addslashes($_REQUEST['id']);
$image= mysql_query("SELECT * from images WHERE id=$id");
$image= mysql_fetch_assoc($image);
$image= base64_decode($image['image']);
![enter image description here][1]header("Content-type: image/jpeg");
echo $image;
?>
答案 0 :(得分:0)
我看到一些问题,您的图片标记看起来很错误
<img src=<?php get.php?id=$lastid >
即使更正了,HTML页面中的标记也是:
<img src=JFIF0[more binary data here] >
当你的意思是
时<img src='get.php?id=<?php echo $lastid ?>' >
生产
<img src='get.php?id=3421' >
我看到的另一个问题是你在将二进制数据插入数据库
之前调用了二进制数据并且如前所述,您应该考虑使用mysqli_ *系列函数来帮助防止sql注入。