form.html如下:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>文件上传</title>
</head>
<body>
<!--enctype属性规定了在提交表单时要用哪种内容类型。
multipart/form-data--表单需要二进制数据时,比如文件内容
-->
<form action="upload_file.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>
upload_file.php如下:
<?php
//允许上传的图片后缀
$allowedExts = array("gif" ,"jepg", "jpg", "png");
$temp = explode(".", $_FILES['file']['name']);
$extension = end($temp); //获取文件后缀名
if ((($_FILES['file']['type'] == 'image/gif')
($_FILES['file']['type'] == 'image/jepg')
($_FILES['file']['type'] == 'image/jpg')
($_FILES['file']['type'] == 'image/png')
($_FILES['file']['type'] == 'image/pjpeg')
($_FILES['file']['type'] == 'image/x-png'))
&& ($_FILES['file']['size'] < 204800) //小于200kb
&& in_array($extension, $allowedExts))
{
if ($_FILES['file']['error'] > 0)
{
echo "错误:" . $_FILES['file']['error'] . '<br>';
}
else
{
echo "上传文件名:" . $_FILES['file']['name'] . '<br>';
echo "文件类型:" . $_FILES['file']['type'] . '<br>';
echo "文件大小:" . ($_FILES['file']['size'] / 1024) . 'KB<br>'; //以字节计
echo "文件临时存储位置:" . $_FILES['file']['tmp_name'] . '<br>';
//判断当前目录下的upload目录是否存在该文件
//如果没有upload目录,你需要创建它,upload目录权限为777
if (file_exists("upload/" . $_FILES['file']['name']))
{
echo $_FILES['file']['name'] . "文件已经存在。"; //文件名英文最好,不然会报错
}
else
{
//如果upload目录不存在该文件则讲文件上传到upload目录下
move_uploaded_file ($_FILES['file']['tmp_name'], "upload/" . $_FILES['file']['name']);
echo "文件存储在:" ."upload/" . $_FILES['file']['name'];
}
}
}
else
{
echo "非法的文件格式";
}
?>
起初我的上传文件由于含有中文,所以,会报错;后来改成英文完全正确!当然还有其他原因,比如目录权限不够,还有路径应该由相对路径改成绝对路径,如下代码:
move_uploaded_file ($_FILES['file']['tmp_name'], "D:/Demo/test/upload/" . $_FILES['file']['name']);