实现思路
HTML 结构:创建一个包含文件输入框和上传按钮的表单。
CSS 样式:美化上传按钮,使其更具吸引力。
JavaScript 验证:在客户端验证文件格式和大小。
PHP 处理:在服务器端再次验证文件格式和大小,并处理文件上传。

代码示例
1. index.html 文件
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>文件上传</title> <link rel="stylesheet" href="styles.css"> </head> <body> <form id="uploadForm" action="upload.php" method="post" enctype="multipart/form-data"> <div> <input type="file" id="fileInput" name="file" accept=".jpg,.jpeg,.png,.pdf"> <label for="fileInput">选择文件</label> </div> <button type="submit">上传</button> </form> <div id="errorMessage" style="color: red;"></div> <script src="script.js"></script> </body> </html>
2. styles.css 文件
.file-upload {
position: relative;
display: inline-block;
}
.file-upload input[type="file"] {
position: absolute;
left: 0;
top: 0;
opacity: 0;
width: 100%;
height: 100%;
cursor: pointer;
}
.file-upload label {
display: inline-block;
background-color: #007BFF;
color: white;
padding: 10px 20px;
border-radius: 5px;
cursor: pointer;
transition: background-color 0.3s ease;
}
.file-upload label:hover {
background-color: #0056b3;
}
button[type="submit"] {
background-color: #28a745;
color: white;
padding: 10px 20px;
border: none;
border-radius: 5px;
cursor: pointer;
transition: background-color 0.3s ease;
}
button[type="submit"]:hover {
background-color: #218838;
}3. script.js 文件
const form = document.getElementById('uploadForm');
const fileInput = document.getElementById('fileInput');
const errorMessage = document.getElementById('errorMessage');
form.addEventListener('submit', function (e) {
const file = fileInput.files[0];
if (file) {
const allowedExtensions = /(\.jpg|\.jpeg|\.png|\.pdf)$/i;
if (!allowedExtensions.exec(file.name)) {
errorMessage.textContent = '只允许上传 JPG、JPEG、PNG 或 PDF 文件。';
e.preventDefault();
return;
}
const maxSize = 5 * 1024 * 1024; // 5MB
if (file.size > maxSize) {
errorMessage.textContent = '文件大小不能超过 5MB。';
e.preventDefault();
return;
}
}
errorMessage.textContent = '';
});4. upload.php 文件
<?php
// 允许的文件类型
$allowedExtensions = array('jpg', 'jpeg', 'png', 'pdf');
// 最大文件大小(5MB)
$maxSize = 5 * 1024 * 1024;
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (isset($_FILES["file"])) {
$file = $_FILES["file"];
$fileName = $file["name"];
$fileSize = $file["size"];
$fileTmpName = $file["tmp_name"];
$fileError = $file["error"];
// 获取文件扩展名
$fileExtension = strtolower(pathinfo($fileName, PATHINFO_EXTENSION));
// 检查文件类型
if (!in_array($fileExtension, $allowedExtensions)) {
echo "只允许上传 JPG、JPEG、PNG 或 PDF 文件。";
exit;
}
// 检查文件大小
if ($fileSize > $maxSize) {
echo "文件大小不能超过 5MB。";
exit;
}
// 检查上传过程中是否有错误
if ($fileError === 0) {
// 生成唯一的文件名
$newFileName = uniqid() . '.' . $fileExtension;
$uploadPath = 'uploads/' . $newFileName;
// 移动文件到指定目录
if (move_uploaded_file($fileTmpName, $uploadPath)) {
echo "文件上传成功!";
} else {
echo "文件上传失败,请稍后再试。";
}
} else {
echo "上传过程中出现错误,请稍后再试。";
}
} else {
echo "未选择文件,请选择要上传的文件。";
}
}
?>代码解释
HTML 部分:创建了一个包含文件输入框和上传按钮的表单,使用 accept 属性限制文件类型。
CSS 部分:美化了上传按钮,使其更具吸引力。
JavaScript 部分:在表单提交时,验证文件格式和大小,如果不符合要求,则阻止表单提交并显示错误信息。
PHP 部分:在服务器端再次验证文件格式和大小,并处理文件上传。如果上传成功,将文件移动到指定目录。
注意事项
请确保在服务器上创建一个名为 uploads 的目录,并且该目录具有写入权限。
可以根据需要修改允许的文件类型和最大文件大小。
以下是将所有代码整合在一个页面中,同时添加美化样式和上传进度条的完整示例:
<!DOCTYPE html>
<html >
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>文件上传</title>
<style>
body {
font-family: Arial, sans-serif;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
height: 100vh;
margin: 0;
background-color: #f4f4f9;
}
.file-upload {
position: relative;
display: inline-block;
margin-bottom: 20px;
}
.file-upload input[type="file"] {
position: absolute;
left: 0;
top: 0;
opacity: 0;
width: 100%;
height: 100%;
cursor: pointer;
}
.file-upload label {
display: inline-block;
background-color: #007BFF;
color: white;
padding: 12px 24px;
border-radius: 5px;
cursor: pointer;
transition: background-color 0.3s ease;
box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}
.file-upload label:hover {
background-color: #0056b3;
}
button[type="submit"] {
background-color: #28a745;
color: white;
padding: 12px 24px;
border: none;
border-radius: 5px;
cursor: pointer;
transition: background-color 0.3s ease;
box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}
button[type="submit"]:hover {
background-color: #218838;
}
#progressBar {
width: 300px;
height: 20px;
background-color: #e9ecef;
border-radius: 5px;
margin-top: 20px;
overflow: hidden;
}
#progress {
height: 100%;
background-color: #007BFF;
width: 0;
transition: width 0.3s ease;
}
#errorMessage {
color: red;
margin-top: 10px;
}
</style>
</head>
<body>
<form id="uploadForm" action="#" method="post" enctype="multipart/form-data">
<div>
<input type="file" id="fileInput" name="file" accept=".jpg,.jpeg,.png,.pdf">
<label for="fileInput">选择文件</label>
</div>
<button type="submit">上传</button>
</form>
<div id="progressBar">
<div id="progress"></div>
</div>
<div id="errorMessage"></div>
<script>
const form = document.getElementById('uploadForm');
const fileInput = document.getElementById('fileInput');
const errorMessage = document.getElementById('errorMessage');
const progress = document.getElementById('progress');
form.addEventListener('submit', function (e) {
e.preventDefault();
const file = fileInput.files[0];
if (file) {
const allowedExtensions = /(\.jpg|\.jpeg|\.png|\.pdf)$/i;
if (!allowedExtensions.exec(file.name)) {
errorMessage.textContent = '只允许上传 JPG、JPEG、PNG 或 PDF 文件。';
return;
}
const maxSize = 5 * 1024 * 1024; // 5MB
if (file.size > maxSize) {
errorMessage.textContent = '文件大小不能超过 5MB。';
return;
}
errorMessage.textContent = '';
// 弹出确认提示框
if (confirm('确定要上传该文件吗?')) {
const xhr = new XMLHttpRequest();
xhr.open('POST', '<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>', true);
xhr.upload.addEventListener('progress', function (e) {
if (e.lengthComputable) {
const percentComplete = (e.loaded / e.total) * 100;
progress.style.width = percentComplete + '%';
}
});
xhr.onreadystatechange = function () {
if (xhr.readyState === 4) {
if (xhr.status === 200) {
alert(xhr.responseText);
} else {
alert('上传失败,请稍后再试。');
}
}
};
const formData = new FormData();
formData.append('file', file);
xhr.send(formData);
}
} else {
errorMessage.textContent = '未选择文件,请选择要上传的文件。';
}
});
</script>
<?php
// 允许的文件类型
$allowedExtensions = array('jpg', 'jpeg', 'png', 'pdf');
// 最大文件大小(5MB)
$maxSize = 5 * 1024 * 1024;
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (isset($_FILES["file"])) {
$file = $_FILES["file"];
$fileName = $file["name"];
$fileSize = $file["size"];
$fileTmpName = $file["tmp_name"];
$fileError = $file["error"];
// 获取文件扩展名
$fileExtension = strtolower(pathinfo($fileName, PATHINFO_EXTENSION));
// 检查文件类型
if (!in_array($fileExtension, $allowedExtensions)) {
echo "只允许上传 JPG、JPEG、PNG 或 PDF 文件。";
exit;
}
// 检查文件大小
if ($fileSize > $maxSize) {
echo "文件大小不能超过 5MB。";
exit;
}
// 检查上传过程中是否有错误
if ($fileError === 0) {
// 生成唯一的文件名
$newFileName = uniqid() . '.' . $fileExtension;
$uploadPath = 'uploads/' . $newFileName;
// 创建 uploads 目录(如果不存在)
if (!is_dir('uploads')) {
mkdir('uploads', 0777, true);
}
// 移动文件到指定目录
if (move_uploaded_file($fileTmpName, $uploadPath)) {
echo "文件上传成功!";
} else {
echo "文件上传失败,请稍后再试。";
}
} else {
echo "上传过程中出现错误,请稍后再试。";
}
} else {
echo "未选择文件,请选择要上传的文件。";
}
}
?>
</body>
</html>分享




发表评论