php实现上传进度条
在PHP中实现文件上传进度条,可以通过结合前端技术和PHP的session.upload_progress机制来实现。以下是具体实现方法:
启用session.upload_progress
在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"
session.upload_progress.freq = "1%"
前端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" value="Upload">
</form>
<div id="progress-container">
<div id="progress-bar"></div>
</div>
后端PHP处理
创建upload.php处理文件上传,同时提供获取进度信息的接口:
<?php
session_start();
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
// 处理文件上传
move_uploaded_file($_FILES['file1']['tmp_name'], '/path/to/uploads/' . $_FILES['file1']['name']);
}
进度查询接口
创建progress.php用于返回当前上传进度:
<?php
session_start();
header('Content-Type: application/json');
$key = ini_get('session.upload_progress.prefix') . $_GET['key'];
if (!empty($_SESSION[$key])) {
$progress = $_SESSION[$key];
echo json_encode([
'bytes_processed' => $progress['bytes_processed'],
'content_length' => $progress['content_length'],
'percent' => round(($progress['bytes_processed'] / $progress['content_length']) * 100, 2)
]);
} else {
echo json_encode(['percent' => 0]);
}
前端JavaScript轮询
使用JavaScript定期查询上传进度并更新进度条:
function fetchProgress(key) {
fetch(`progress.php?key=${key}`)
.then(response => response.json())
.then(data => {
document.getElementById('progress-bar').style.width = data.percent + '%';
if (data.percent < 100) {
setTimeout(() => fetchProgress(key), 500);
}
});
}
document.querySelector('form').addEventListener('submit', function(e) {
const key = this.elements['PHP_SESSION_UPLOAD_PROGRESS'].value;
fetchProgress(key);
});
CSS样式
添加简单的CSS样式美化进度条:
#progress-container {
width: 100%;
background-color: #f0f0f0;
margin-top: 10px;
}
#progress-bar {
height: 20px;
background-color: #4CAF50;
width: 0%;
transition: width 0.3s;
}
这种方法利用了PHP内置的上传进度跟踪功能,通过前端轮询后端接口获取实时进度数据,实现了无需额外扩展的上传进度条功能。







