您当前的位置:首页 > 计算机 > 编程开发 > PHP

原生PHP 图片上传并渲染指定dom中

时间:08-05来源:作者:点击数:

原生PHP 图片上传并渲染指定dom中

html:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
     <script src="jquery-3.6.0.min.js"></script>    
</head>

<style>
	.imge img{
		width: 150px;
		height: 80px;
		margin-top: 70px;
		margin-left: 80px;
	}
</style>


<body>
	<form id="forms"  >
		<label>上传图片:<input type="file" id="file" name="file"></label>
		
		<input type="button" value="上传" id="sub">
	</form>
	<div class="imge"></div>

    <script>

let sub=document.getElementById('sub');
sub.onclick=function(){
	var form = new FormData(document.getElementById('forms'));
		console.log(form);
		$.ajax({
			url: "../index.php",
			type: 'POST',
			data: form,
			processData: false,
			contentType: false,
			success: function(data) {
			console.log(data);
			document.getElementsByClassName('imge')[0].innerHTML = data;
			},
		});
}


        </script>
</body>
</html>

php:

<?php

$allowedExts = array("gif", "jpeg", "jpg", "png");
$temp = explode(".", $_FILES["file"]["name"]);
// var_dump($_FILES["file"]);

$extension = end($temp);     // 获取文件后缀名
if (in_array($extension, $allowedExts))
{
	if ($_FILES["file"]["error"] > 0)
	{
		echo "错误:: " . $_FILES["file"]["error"] . "<br>";
	}
	else
	{
		if (file_exists("upload/" . $_FILES["file"]["name"]))
		{
			echo $_FILES["file"]["name"] . " 文件已经存在。 ";
		}
		else
		{
			move_uploaded_file($_FILES["file"]["tmp_name"], "upload/" . $_FILES["file"]["name"]);
            $uploadimg="upload/" . $_FILES["file"]["name"];

            $dbhost = 'localhost';  // mysql服务器主机地址
			$dbuser = 'root';            // mysql用户名
			$dbpass = '123456';          // mysql用户名密码
			$conn = mysqli_connect($dbhost, $dbuser, $dbpass);
			mysqli_select_db( $conn, 'mysql' );
			mysqli_query($conn , "set names utf8");
            //插入数据库
		$sql = "INSERT INTO imgs ".
       		 "(img) ".
        	"VALUES ".
       		 "('$uploadimg')";
 		$retval = mysqli_query( $conn, $sql );
	 	

		$select = "select * from imgs where img='$uploadimg'";

		$retvals = mysqli_query( $conn, $select );
		while($row = mysqli_fetch_array($retvals,MYSQLI_ASSOC)){
			echo "<img src='{$row['img']}'>";
			
		}
		if(! $retval )
		{
 		 die('无法插入数据: ' . mysqli_error($conn));
		}
		}
	}
}
else
{
	echo "非法的文件格式";
}







?>

 

方便获取更多学习、工作、生活信息请关注本站微信公众号城东书院 微信服务号城东书院 微信订阅号
推荐内容
相关内容
栏目更新
栏目热门