日期:2013-07-09  浏览次数:20527 次

PHP代码:--------------------------------------------------------------------------------

<?php
// 文件名:filedb.php 将文件储存到数据库中
/*
将文件上传存入 MySQL 数据库的例子
数据表的结构如下:
CREATE TABLE files (
id int(4) NOT NULL auto_increment,
filename varchar(64),
filesize int(16),
filetype varchar(64),
filecontent longblob,
remark text,
PRIMARY KEY (id)
);
*/
// 设定系统参数变量,根据需要修改
$DB_SERVER = "127.0.0.1"; # 数据库连接字
$DB_USER = "root"; # 用户名
$DB_PASS = ""; # 密码
$DB_NAME = "article"; # 数据库名
$TABLE_NAME = "files"; # 数据表名
$HANDLER_SCRIPT = "mysql数据库显示文件.php"; # 处理数据的脚本文件名
$PHP_SELF=$_SERVER['PHP_SELF'];
?>
<html>
<head>
<title>将文件存入数据库</title>

<style>
caption { background-color: #E6F4FF; font-size:14px}
td { background-color: #E6F4FF; font-size:12px}
th { background-color: #FFCC00; font-size:12px}
div {font-size:12px}
</style>
</head>
<body>
<form enctype='multipart/form-data' method='post'>
<table cellspacing=1 cellpadding=5 >
<caption>文件存入数据库管理器</caption>
<input type='hidden' name='MAX_FILE_SIZE' value=10489760>
<tr>
<td>上传文件:</td>
<td><input type='file' name='userfile'></td>
</tr>
<tr valign=top>
<td>文件说明:</td>
<td><textarea name='description' rows='4' cols='40'></textarea></td>
</tr>
<tr>
<td colspan=2 align=center><input type='submit' name='submit' value=' 上传 '>
</tr>
</table>
</form>
<?php
if (isset($_POST["submit"])) // 表单被提交后执行以下代码
{
if (!is_uploaded_file($_FILES['userfile']['tmp_name'])) // 检查文件是否上传成功
{
die("文件上传失败!");
}
$link = mysql_connect($DB_SERVER, $DB_USER, $DB_PASS) // 连接数据库
or die("连接数据库失败!");
mysql_select_db($DB_NAME);
$filename = addslashes($_FILES['userfile']['name']); # 为了正确保存入数据库,
$filesize = addslashes($_FILES['userfile']['size']); # 对所有的插入数据都要
$filetype = addslashes($_FILES['userfile']['type']); # 进行 addslashes 操作
// 读入上传的文件并做预处理 #
$tmp_name = $_FILES['userfile']['tmp_name'];
$fd = fopen ($tmp_name, "rb");
$contents = fread ($fd, filesize ($tmp_name));
fclose ($fd);
$filecontent = addslashes($contents);
$tmp_name = $_FILES['userfile']['tmp_name'];
$fd = fopen ($tmp_name, "rb");
$contents = fread ($fd, filesize ($tmp_name));
fclose ($fd);
$filecontent = addslashes($contents);
$remark = addslashes($_POST['description']);

$query_string = "INSERT INTO $TABLE_NAME VALUES ('', '$filename', '$filesize', '$filetype', '$filecontent', '$remark')";
$result = mysql_query($query_string) or die("数据插入失败!"); # 进行数据插入操作
echo "<div id='info'>保存成功!<br>\n";
echo "文件名 :{$_FILES['userfile']['name']}<br>\n";
echo "文件大小:{$_FILES['userfile']['size']} 字节<br>\n";
echo "文件类型:{$_FILES['userfile']['type']}</div>\n";
echo "<input type=\"submit\" value=刷新 onclick=\"window.location='$PHP_SELF'\">";
}
echo "
<table border=2 bordercolor=#055AA0 cellspacing=0 width=840 cellpadding=0 style=\"border-collapse: collapse ;LEFT: 0px; WORD-WRAP: break-word; word-break:break-all\" >
<tr>
<th width=>ID</th>
<th>文件名</th>
<th>文件大小</th>
<th>文件类型</th>