今日小任务是实现上传图片到PHP
使用form标签实现上传
<!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>文件上传</title>
</head>
<body>
<form action="controller/index.php" method="post" enctype="multipart/form-data">
<label for="file">文件名:</label>
<input type="file" name="file" id="file"><br>
<input type="submit" name="submit" value="提交">
</form>
</body>
</html>
action属性设定了要往哪里传递数据;
method设置上传方式,一般使用post;
enctype="multipart/form-data"在上传文件是必须添加设定
使用这种方法在点击submit提交按钮时会跳转到action设定的文件,然后在php文件内处理传入的数据
<?php
// 允许上传的图片后缀
$allowedExts = array("gif", "jpeg", "jpg", "png");
$temp = explode(".", $_FILES["file"]["name"]);
$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{
// 如果 upload 目录不存在该文件则将文件上传到 upload 目录下
$store = "upload/" . $_FILES["file"]["name"];
move_uploaded_file($_FILES["file"]["tmp_name"], $store);
$dbhost = 'localhost';
$dbroot = 'root';
$dbpass = '123456';
$conn = mysqli_connect($dbhost,$dbroot,$dbpass);//连接MySQL服务器
// $createdb = mysqli_query($conn,'create database files');//创建数据库
mysqli_select_db($conn,'files');//选择数据库
mysqli_set_charset($conn,'utf8');
//创建数据表
// $createtable = "create table file(".
// "id int(11) not null auto_increment,".
// "name varchar(1000) not null,".
// "primary key (id)".
// ")engine=InnoDB charset=utf8";
// $createtab = mysqli_query($conn,$createtable);
// var_dump($createtab);
//插入数据字符串
$insert = "insert into file(name)".
"values".
"('$store')";
$into = mysqli_query($conn,$insert);//请求插入数据
$select = "select distinct name from file where name='$store';";//查询数据字符串
$selecting = mysqli_query($conn,$select);//请求查询数据
while($row = mysqli_fetch_array($selecting, MYSQLI_ASSOC)){//循环将查询到的数据提取出来
// echo "imgid=".$row['id'];
echo "<img src="$row['name']" style="width:500px;">";
}
}
}
}else{
echo "非法的文件格式";
}
?>
这里没有返回到html页面,直接在php页面写入了图片,如果要返回html页面,可以使用echo输出javascript代码中的location.href跳转,或者使用php中的header函数:header("location: 路径");location与:中间不能有空格,否则不会执行