php 上传图片,一般都使用move_uploaded_file方法保存在服务器上。但如果一个网站有多台服务器,就需要把图片发布到所有的服务器上才能正常使用(使用图片服务器的除外)
如果把图片数据保存到数据库中,多台服务器间可以实现文件共享,节省空间。
首先图片文件是二进制数据,所以需要把二进制数据保存在mysql数据库。
mysql数据库提供了blob类型用于存储大量数据,blob是一个二进制对象,能容纳不同大小的数据。
blob类型有以下四种,除存储的最大信息量不同外,其他都是一样的。可根据需要使用不同的类型。
tinyblob 最大 255b
blob 最大 65k
mediumblob 最大 16m
longblob 最大 4g
数据表photo,用于保存图片数据,结构如下:
create table `photo` ( `id` int(10) unsigned not null auto_increment, `type` varchar(100) not null, `binarydata` mediumblob not null, primary key (`id`)) engine=myisam default charset=latin1 auto_increment=1 ;
upload_image_todb.php
<?php// 连接数据库$conn=@mysql_connect("localhost","root","") or die(mysql_error());@mysql_select_db('demo',$conn) or die(mysql_error());// 判断action$action = isset($_request['action'])? $_request['action'] : '';// 上传图片if($action=='add'){ $image = mysql_escape_string(file_get_contents($_files['photo']['tmp_name'])); $type = $_files['photo']['type']; $sqlstr = "insert into photo(type,binarydata) values('".$type."','".$image."')"; @mysql_query($sqlstr) or die(mysql_error()); header('location:upload_image_todb.php'); exit();// 显示图片}elseif($action=='show'){ $id = isset($_get['id'])? intval($_get['id']) : 0; $sqlstr = "select * from photo where id=$id"; $query = mysql_query($sqlstr) or die(mysql_error()); $thread = mysql_fetch_assoc($query); if($thread){ header('content-type:'.$thread['type']); echo $thread['binarydata']; exit(); }}else{// 显示图片列表及上传表单?><!doctype html public "-//w3c//dtd html 4.01 transitional//en" "http://www.w3.org/tr/html4/loose.dtd"><html> <head> <meta http-equiv="content-type" content="text/html; charset=utf-8"> <title> upload image to db demo </title> </head> <body> <form name="form1" method="post" action="upload_image_todb.php" enctype="multipart/form-data"> <p>图片:<input type="file" name="photo"></p> <p><input type="hidden" name="action" value="add"><input type="submit" name="b1" value="提交"></p> </form><?php $sqlstr = "select * from photo order by id desc"; $query = mysql_query($sqlstr) or die(mysql_error()); $result = array(); while($thread=mysql_fetch_assoc($query)){ $result[] = $thread; } foreach($result as $val){ echo '<p><img src="upload_image_todb.php?action=show&id='.$val['id'].'&t='.time().'" width="150"></p>'; }?> </body></html><?php}?>
本文讲解了通过php 上传图片保存到数据库的实例讲解,更多相关内容请关注。
相关推荐:
如何通过php 发送与接收流文件
如何通过php 对图片局部打马赛克
如何通过php 获取文件mime类型的方法讲解
以上就是通过php 上传图片保存到数据库的实例讲解的详细内容。