You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

请求为双文件结构的PHP文件上传脚本添加进度条

给PHP文件上传添加进度条的实现方案

我来帮你搞定这个文件上传进度条的需求!基于你现有的PHP脚本,我们可以用HTML5的File API结合AJAX来实现实时进度显示,不用依赖额外的库,简单高效。

第一步:修改前端表单(index.php)

我们需要把传统的表单提交改成AJAX异步上传,同时添加进度条元素和监听上传进度的逻辑:

<!doctype html>
<html>
<head>
    <title>文件上传</title>
    <style>
        .progress-container {
            width: 100%;
            height: 20px;
            border: 1px solid #ccc;
            border-radius: 5px;
            margin-top: 10px;
            display: none;
        }
        .progress-bar {
            height: 100%;
            background-color: #4CAF50;
            width: 0%;
            border-radius: 5px;
            transition: width 0.3s ease;
        }
    </style>
</head>
<body>
    <form enctype="multipart/form-data" id="uploadForm">
        <input type="hidden" name="MAX_FILE_SIZE" value="4294967296">
        上传此文件:<input name="userfile" type="file" id="fileInput">
        <input type="button" value="上传" onclick="uploadFile()">
        <div class="progress-container" id="progressContainer">
            <div class="progress-bar" id="progressBar"></div>
        </div>
        <p id="statusText"></p>
    </form>

    <script>
        function uploadFile() {
            const fileInput = document.getElementById('fileInput');
            const file = fileInput.files[0];
            if (!file) {
                alert('请选择要上传的文件');
                return;
            }

            // 用FormData包装文件数据,模拟表单提交
            const formData = new FormData();
            formData.append('userfile', file);
            formData.append('MAX_FILE_SIZE', '4294967296');

            const xhr = new XMLHttpRequest();
            const progressContainer = document.getElementById('progressContainer');
            const progressBar = document.getElementById('progressBar');
            const statusText = document.getElementById('statusText');

            // 上传开始前显示进度条
            progressContainer.style.display = 'block';

            // 监听上传进度事件
            xhr.upload.addEventListener('progress', function(e) {
                if (e.lengthComputable) {
                    // 计算已上传百分比
                    const percentComplete = (e.loaded / e.total) * 100;
                    // 更新进度条宽度和状态文本
                    progressBar.style.width = percentComplete + '%';
                    statusText.textContent = `已上传:${Math.round(percentComplete)}%`;
                }
            });

            // 上传完成后的处理
            xhr.addEventListener('load', function() {
                if (xhr.status === 200) {
                    statusText.textContent = '上传完成!';
                    // 这里可以根据后端返回的信息做进一步处理,比如显示成功提示
                    console.log('服务器返回:', xhr.responseText);
                } else {
                    statusText.textContent = '上传失败,请重试';
                }
            });

            // 处理上传错误
            xhr.addEventListener('error', function() {
                statusText.textContent = '上传过程中发生错误';
            });

            // 发送上传请求到后端
            xhr.open('POST', 'upload_file.php');
            xhr.send(formData);
        }
    </script>
</body>
</html>

第二步:调整后端处理脚本(upload_file.php)

后端基本保持你原来的逻辑,只需要确保上传目录存在,避免报错:

<?php
// 设置上传目录,确保目录存在
$targetDir = './uploads/';
if (!is_dir($targetDir)) {
    mkdir($targetDir, 0755, true);
}

$targetFile = $targetDir . basename($_FILES['userfile']['name']);
$uploadOk = 1;
$fileType = strtolower(pathinfo($targetFile,PATHINFO_EXTENSION));

// 检查文件是否已存在
if (file_exists($targetFile)) {
    echo "抱歉,文件已经存在。";
    $uploadOk = 0;
}

// 检查文件大小是否超出限制
if ($_FILES['userfile']['size'] > 4294967296) {
    echo "抱歉,你的文件太大了。";
    $uploadOk = 0;
}

// 尝试上传文件
if ($uploadOk == 1) {
    if (move_uploaded_file($_FILES['userfile']['tmp_name'], $targetFile)) {
        echo "文件 ". htmlspecialchars( basename( $_FILES['userfile']['name'])). " 已经成功上传。";
    } else {
        echo "抱歉,上传文件时发生错误。";
    }
}
?>

关键注意事项

  1. 服务器PHP配置调整:因为你设置了4G的文件大小限制,需要修改php.ini中的以下参数:

    • upload_max_filesize = 4G
    • post_max_size = 4G
    • max_execution_time = 300(根据文件大小调整,确保上传过程不超时)
    • max_input_time = 300
  2. 样式自定义:你可以修改CSS中的.progress-container和.progress-bar样式,调整进度条的颜色、高度、圆角等,适配你的页面风格。

  3. 兼容性:这个方案基于HTML5的File API和XMLHttpRequest2,现在主流浏览器(Chrome、Firefox、Edge等)都支持,如果你需要兼容非常老旧的浏览器,可能需要额外的 fallback 方案,但一般来说现在不需要考虑。

内容的提问来源于stack exchange,提问作者Giampiero Coccalo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.22 08:56:50