php实现上传进度条
PHP 文件上传进度条实现方法
在PHP中实现文件上传进度条需要结合前端和后端技术,以下是一种常见的实现方案:
使用 session.upload_progress 功能
PHP 5.4+ 内置了上传进度跟踪功能,通过配置 php.ini 启用:
session.upload_progress.enabled = On
session.upload_progress.cleanup = On
session.upload_progress.prefix = "upload_progress_"
session.upload_progress.name = "PHP_SESSION_UPLOAD_PROGRESS"
前端HTML表单需要包含特殊字段:
<form action="upload.php" method="POST" enctype="multipart/form-data">
<input type="hidden" name="<?php echo ini_get('session.upload_progress.name'); ?>" value="123">
<input type="file" name="file1">
<input type="submit">
</form>
后端PHP脚本获取进度:
$key = ini_get('session.upload_progress.prefix') . $_POST[ini_get('session.upload_progress.name')];
$progress = $_SESSION[$key];
前端AJAX轮询实现
创建一个进度检查接口:
// progress.php
session_start();
$key = ini_get('session.upload_progress.prefix') . $_GET['progress_key'];
if (isset($_SESSION[$key])) {
$progress = $_SESSION[$key];
echo json_encode([
'received' => $progress['bytes_processed'],
'total' => $progress['content_length']
]);
}
前端JavaScript代码:
function checkProgress(progressKey) {
fetch(`progress.php?progress_key=${progressKey}`)
.then(response => response.json())
.then(data => {
const percent = Math.round((data.received / data.total) * 100);
updateProgressBar(percent);
if (percent < 100) {
setTimeout(() => checkProgress(progressKey), 500);
}
});
}
使用第三方库
对于更复杂的需求,可以考虑以下方案:
- 使用jQuery插件如jQuery-File-Upload
- 使用Dropzone.js等现代文件上传库
- 使用Plupload等支持多运行时环境的库
注意事项
确保服务器配置允许大文件上传:
upload_max_filesize = 100M
post_max_size = 100M
max_execution_time = 300
现代浏览器支持XMLHttpRequest Level 2的进度事件,可以更高效地实现进度跟踪:
xhr.upload.addEventListener('progress', function(e) {
if (e.lengthComputable) {
const percent = Math.round((e.loaded / e.total) * 100);
// 更新进度条
}
}, false);






