html+CSS+JS一个简单的上传页面

落寞

实现思路

HTML 结构:创建一个包含文件输入框和上传按钮的表单。

CSS 样式:美化上传按钮,使其更具吸引力。

JavaScript 验证:在客户端验证文件格式和大小。

PHP 处理:在服务器端再次验证文件格式和大小,并处理文件上传。

html+CSS+JS一个简单的上传页面.jpg

代码示例

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>



收起




分享


文章版权声明:
1、本网站名称:菜鸟小站
2、本站永久网址:https://mo.cnzv.cc
3、本网站的文章部分内容可能来源于网络,如有侵权,请联系站长 QQ7419838 进行删除处理。
4、本站一切资源不代表本站立场,并不代表本站赞同其观点和对其真实性负责。
5、本站一律禁止以任何方式发布或转载任何违法的相关信息,访客发现请向站长举报

发表评论

快捷回复: 表情:
AddoilApplauseBadlaughBombCoffeeFabulousFacepalmFecesFrownHeyhaInsidiousKeepFightingNoProbPigHeadShockedSinistersmileSlapSocialSweatTolaughWatermelonWittyWowYeahYellowdog
评论列表 (有 20 条评论,727人围观)
网友昵称:咋党冰
咋党冰 V 铁粉 20楼
2025-07-15 回复
赞,顶帖超有参考作用
网友昵称:蒜
V 铁粉 19楼
2025-07-12 回复
分享很有用,点赞表支持啦
网友昵称:自我主宰
自我主宰 V 铁粉 18楼
2025-07-11 回复
分享超给力,点赞大拇指
网友昵称:素颜亦倾城
素颜亦倾城 V 铁粉 17楼
2025-07-07 回复
感谢分享,让我收获多多
网友昵称:病态污的撩汉高手
病态污的撩汉高手 V 铁粉 16楼
2025-07-04 回复
感谢分享,开阔我的眼界
网友昵称:大宝巨巨
大宝巨巨 V 铁粉 15楼
2025-06-23 回复
不错哦喜欢嘿嘿
网友昵称:橙依
橙依 V 铁粉 14楼
2025-06-18 回复
赞,顶帖真的超有水平
网友昵称:橙依
橙依 V 铁粉 13楼
2025-05-24 回复
这个不错
网友昵称:蒙意
蒙意 V 铁粉 12楼
2025-05-15 回复
感谢分享,充满人生哲理
网友昵称:病态污的撩汉高手
病态污的撩汉高手 V 铁粉 11楼
2025-05-13 回复
谢谢楼主的辛苦分享
网友昵称:究赊粹
究赊粹 V 铁粉 10楼
2025-04-22 回复
加油
网友昵称:躺肇散
躺肇散 V 铁粉 9楼
2025-04-08 回复
加油
网友昵称:生人勿扰
生人勿扰 V 铁粉 8楼
2025-04-08 回复
赞,顶帖超有借鉴价值
网友昵称:旅蛮良
旅蛮良 V 铁粉 7楼
2025-04-02 回复
期待更多东西
网友昵称:惠子
惠子 V 铁粉 6楼
2025-03-31 回复
分享超实用,点赞必须的
网友昵称:录葡
录葡 V 铁粉 地板
2025-03-31 回复
支持分享,文章相当出彩
网友昵称:因
V 铁粉 凉席
2025-03-30 回复
支持发布,内容值得点赞
网友昵称:爱恨情仇
爱恨情仇 V 铁粉 板凳
2025-03-17 回复
赞,顶帖内容超有深度
网友昵称:甘革
甘革 V 铁粉 椅子
2025-03-13 回复
嘻嘻不错支持一个
网友昵称:塔又
塔又 V 铁粉 沙发
2025-03-11 回复
赞,顶帖角度新颖独特
取消
微信二维码
微信二维码
支付宝二维码