写一个上传文件的html和对应的php
时间: 2024-05-09 22:20:58 浏览: 7
HTML代码:
```
<!DOCTYPE html>
<html>
<head>
<title>上传文件</title>
</head>
<body>
<h1>上传文件</h1>
<form method="post" enctype="multipart/form-data" action="upload.php">
<label>选择文件:</label>
<input type="file" name="fileToUpload" id="fileToUpload"><br><br>
<input type="submit" value="上传" name="submit">
</form>
</body>
</html>
```
PHP代码:
```
<?php
$target_dir = "uploads/"; //上传文件保存的目录
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]); //上传文件的完整路径
$uploadOk = 1; //上传是否成功的标志
//检查文件是否已经存在
if (file_exists($target_file)) {
echo "文件已经存在!";
$uploadOk = 0;
}
//检查文件大小
if ($_FILES["fileToUpload"]["size"] > 500000) {
echo "文件太大!";
$uploadOk = 0;
}
//允许的文件格式
$allowedFileType = array("jpg", "jpeg", "png", "gif");
$fileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));
//检查文件格式
if(!in_array($fileType, $allowedFileType)) {
echo "只允许上传" . implode(", ",$allowedFileType) . "格式的文件!";
$uploadOk = 0;
}
//检查上传是否成功
if ($uploadOk == 0) {
echo "文件上传失败!";
} else {
if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
echo "文件" . basename($_FILES["fileToUpload"]["name"]) . "上传成功!";
} else {
echo "文件上传失败!";
}
}
?>
```