很奇怪,直接用file_get_contents存入數據庫成功后,結果讀取的時候圖片不能顯示,后來解決方法是什么!!是用了下base64編碼。。。不多說直接上圖。
1.這是upload.php
<?php include('./conn.php'); if ($_POST['submit']) { if ($_FILES['image']['size']) { $names = $_FILES['image']['name']; $arr = explode('.', $names); $name = $arr[0]; //圖片名稱 $date = date('Y-m-d H:i:s'); //上傳日期 $fp = fopen($_FILES['image']['tmp_name'], 'rb'); $type = $_FILES['image']['type']; $file_uploads = file_get_contents($_FILES['image']['tmp_name']); $file_uploads = base64_encode($file_uploads); if (!$fp) { showInfo('讀取圖片失敗!'); } else { if ($image) { $q = "insert into image (name, pic, type, date) values ('$name','$file_uploads','$type','$date')"; $result = mysql_query($q); if ($result) { showInfo('上傳成功!'); } else { showInfo('上傳失敗!'); } mysql_close($link); } else { showInfo('請選擇要上傳的文件!'); } } } else { showInfo('請選擇要上傳的文件!'); } } function showInfo($info) { echo "<html><head><meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" />"; echo "<meta http-equiv='refresh' content='1;url=show.php'>"; echo "</head>"; echo "<body>" . $info . "……</body>"; echo "</html>"; } ?>
2.image.php用於從數據庫中讀取圖片
<?php include('./conn.php'); $id = $_GET['id']; $sql = "select * from image where id='$id'"; $result = mysql_query($sql); if (!$result) die("讀取圖片失敗!"); $num = mysql_num_rows($result); if ($num < 1) die("暫無圖片"); $obj = mysql_fetch_object($result); $data = base64_decode($obj->pic); //Base64解碼 $type = mysql_result($result, 0, 'type'); header("Content-type: $type"); echo $data; ?>
3.show.php顯示和上傳圖片
<?php include('./conn.php'); ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" lang="en_US" xml:lang="en_US"> <head> <meta http-equive="Content-Type" content=text/html charset=utf-8> <title> </title> </head> <body> <form method='post' action='./upload.php' enctype="multipart/form-data"> <input type="file" name="image" /> <input type="submit" name="submit" value="上傳" /> </form> <!-----------顯示圖片---------------------> <table> <?php $ret = mysql_query('select * from image order by id desc'); if ($ret) { while ($row = mysql_fetch_array($ret)) { ?> <tr> <td style='width:170px;'> <img src="image.php?id=<?php echo $row[id]; ?>" width="170" height="150" border="0"> <div style='text-align:center;'><?php echo $row['name']; ?></div> <?php echo $row['date']; ?> </td> </tr> <?php } } ?> </table> <!-----------/顯示圖片---------------------> </body> </html>
最后運行結果:
總結:網上的都是坑爹么?誰有其他不用base64編碼的方法能否告知?