PHP部分--图片上传服务器、图片路径存入数据库,并读取

html页面

<!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">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>无标题文档</title>
</head>

<body>
<form action="shangchuan.php" method="post" enctype="multipart/form-data">
    <input type="file" name="file" />
    <input type="submit" value="上传" />
</form>
</body>
</html>

php处理页面

<?php
if($_FILES["file"]["error"])
{
    echo $_FILES["file"]["error"];
}
else
{
    //控制上传文件的类型,大小
    if(($_FILES["file"]["type"]=="image/jpeg" || $_FILES["file"]["type"]=="image/png") && $_FILES["file"]["size"]<1024000)
    {
        //找到文件存放的位置
        $filename = "./file/".date("YmdHis").$_FILES["file"]["name"];
        
        //转换编码格式
        $filename = iconv("UTF-8","gb2312",$filename);
        
        //判断文件是否存在
        if(file_exists($filename))
        {
            echo "该文件已存在!";
        }
        else
        {
            //保存文件
            move_uploaded_file($_FILES["file"]["tmp_name"],$filename);
        }
    }
    else
    {
        echo "文件类型不正确!";
    }
}

 把图片路径存入数据库(在上传成功下面调用数据库存入)

<?php
include("./gongju/DBDA.class.php");
if($_FILES["file"]["error"])
{
    echo $_FILES["file"]["error"];
}
else
{
    //控制上传文件的类型,大小
    if(($_FILES["file"]["type"]=="image/jpeg" || $_FILES["file"]["type"]=="image/png") && $_FILES["file"]["size"]<1024000)
    {
        //找到文件存放的位置
        $filename = "./file/".date("YmdHis").$_FILES["file"]["name"];
        
        //转换编码格式
        $filename = iconv("UTF-8","gb2312",$filename);
        
        //判断文件是否存在
        if(file_exists($filename))
        {
            echo "该文件已存在!";
        }
        else
        {
            //保存文件
            move_uploaded_file($_FILES["file"]["tmp_name"],$filename);
            
            $db=new DBDA();
            $sql="insert into image values('','{$filename}')";
            if($db->Query($sql,0))
            {
                echo "数据插入数据库";
                }
                else
                {
                    echo "数据未插入数据库";
                    };
            
        }
    }
    else
    {
        echo "文件类型不正确!";
    }
}

从数据库中调用图片路径,并读取图片

<?php
include("./gongju/DBDA.class.php");
$db=new DBDA();
$sql="select img from image where ids=1";
$lujing=$db->StrQuery($sql);
echo $lujing;
echo "<img src='{$lujing}'/>";
?>
原文地址:https://www.cnblogs.com/xingyue1988/p/6277002.html