我在上傳圖像時遇到了顯示圖像的問題。它將所有數據插入到mysql中,但它們不會在本地主機上顯示爲預覽圖像。它只是顯示爲一個斷開的鏈接。從圖像檢索圖像使用PHP上傳
這裏是我以前使用文件上傳的圖像插入到數據庫的代碼:
<?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;
?>
做**不**使用此代碼。 mysql _ *()函數被棄用,addslashes()是一個可悲的USELESS塊垃圾,並且您不應該將原始圖像數據存儲在數據庫中,而沒有很好的理由。另外,您的圖像** NOT **無論如何都是以base64格式存儲的,因此您正在解碼無效數據。 –
lol你爲什麼會添加原始數據。圖像應該存儲在服務器上,而不是存儲在數據庫中。 @MarcB在這裏推動一個非常強大的點 - 不要使用這個代碼。 –