kglife developer's blog | our web,our life

九/09

23

上传文件到MYSQL数据库中

假如我们现在从一个页面中提交一个文件到PHP文件中处理,代码如下(省略了html提交页面)

 PHP |  copy |? 
01
< ?php
02
     $filename = $_FILES['userfile']['tmp_name'];
03
            if($_FILES['userfile']['size']&lt;100) exit("请选择文件");
04
            $fp = fopen($filename,   "rb");
05
            $picture = fread($fp,filesize($filename));
06
            $picture = base64_encode($picture);
07
            fclose($fp);
08
            $data['p_pic'] = $picture;
09
            $data['type'] = $_FILES['userfile']['type'];
10
            $data['file_name'] = $_FILES['userfile']['name'];
11
            $data['file_size'] = $_FILES['userfile']['size'];
12
            $data['content'] = $_POST['content'];
13
            $connect =MYSQL_CONNECT("localhost","root","") or die("Unable to connect to MySQL server"); 
14
            mysql_select_db( "test") or die("Unable to select database");
15
            $result=MYSQL_QUERY( "INSERT INTO  (p_pic,type,file_name,file_size,filetype,content) VALUES
16
 ('$data[p_pic]','$data[type]','$data[file_name]','$data[file_size]','$data[content]')"); 
17
 $id= mysql_insert_id();
18
 MYSQL_CLOSE();
19
            header('Content-Type: text/html; charset=utf-8');
20
            if($res) {
21
                echo "添加成功,调用地址是:<a target=\"_blank\" href=\"你的地址/getPic/".$res."\">打开";
22
            } else {
23
                echo "上传出错了" ;
24
            }
25
?><!--wp_fromhtmlpreview_devfmt-->
26
 PHP |  copy |? 
01
< ?php
02
        $id = intval($_GET['getPic']);
03
 $connect =MYSQL_CONNECT("localhost","root","") or die("Unable to connect to MySQL server"); 
04
        mysql_select_db( "test") or die("Unable to select database");
05
        $res = mysql_query( "SELECT * FROM attach WHERE id=$id"); 
06
        if(!$res) {
07
            exit();
08
        }
09
 While ($row=mysql_fetch_object($res)){
10
 $data = $row->p_pic;
11
 }
12
        $data = base64_decode($res['p_pic']);
13
        if(preg_match('/image\//i',$res['type'])) {
14
            header("Content-type:$res[type]");
15
            header("Accept-Length:".$res['file_size']);
16
            header("Accept-Ranges:bytes");
17
            header("Content-Disposition: filename=".$res['file_name']);
18
        } else {
19
            header("Content-type:application/octet-stream");
20
            header("Accept-Ranges:bytes");
21
            header("Accept-Length:".$res['file_size']);
22
            header("Content-Disposition:attachment;filename=".$res['file_name']);
23
        }
24
        echo   $data;
25
        exit;
26
?>

以上代码还没有经过测试,不过大概思路就是这样,希望大家能理解.

· · ·

Comments are closed.

<<

>>