您的位置:首页 > 编程语言 > PHP开发

php将图片以二进制存到mysql中的方法

2013-12-10 00:21 453 查看
很奇怪,直接用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编码的方法能否告知?
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: