// 数据库连接文件,conn.php /* blob 类型最长只能存65535个字节, 所以保存图片时,可用更大的类型, mediumblog/longblob */ $conn = mysql_connect('localhost', 'root', ''); mysql_select_db('test', $conn); mysql_query("set names utf8"); //上传图片处理 upload.php header("Content-type:text/html;charset=utf-8"); include('./conn.php'); if($_POST['submit']) { if($_FILES['image']['size']) { $name = $_FILES['image']['name']; $arr = explode('.',$name); $name = $arr[0]; $date = date('Y-m-d H:i:s'); $fp = fopen($_FILES['image']['tmp_name'], 'rb'); $type = $_FILES['image']['type']; if(!$fp) { echo('读取图片失败!'); }else { $image = addslashes(fread($fp, filesize($_FILES['image']['tmp_name']))); if($image) { $q = "insert into image(name,pic,type,date) values ('{$name}', '{$image}', '{$type}', '{$date}')"; $result = mysql_query($q); if($result) { echo('上传成功'); }else { echo ('上传失败'); } } } }else { echo('请选择上传的图片'); } } // 读取图片文件: image.php include('./conn.php'); $id = $_GET['id']; $sql = "select * from image where id = '{$id}'"; $result = mysql_query($sql, $conn); if(!$result) { die('读取数据库图片失败'); } $num = mysql_num_rows($result); if($num <1) { die('暂无图片!!'); } $row = mysql_fetch_assoc($result); $data = $row['pic']; $type = $row['type']; header("Content-type:$type"); echo $data; // 显示及上传文件: index.php <!doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <title>图片,文件上传</title> </head> <body> <?php include('./conn.php'); ?> <form method = 'post' action='./upload.php' enctype="multipart/form-data"> <input type="file" name="image" /> <input type="submit" name="submit" value="submit" /> </form> <hr /> <?php $ret = mysql_query("select * from image order by id desc"); while($row = mysql_fetch_assoc($ret)) { ?> <img src="image.php?id=<?php echo $row['id']; ?>" /> <?php echo $row['date']; } ?> </body> </html>