当上传较大文件或网络环境较差时,为了提升用户体验,需要通过给用户一定的反馈,告知用户当前进度。
php5.4之后提供了session扩展,通过开启php.ini相应属性来实现。
session.upload_progress.enabled 是否启用上传进度报告(默认开启) 1为开启,0为关闭
session.upload_progress.cleanup 是否在上传完成后及时删除进度数据(默认开启, 推荐开启)
session.upload_progress.prefix[=upload_progress_] 进度数据将存储在_SESSION[session.upload_progress.prefix . _POST[session.upload_progress.name]]
session.upload_progress.name[=PHP_SESSION_UPLOAD_PROGRESS] 如果_POST[session.upload_progress.name]没有被设置, 则不会报告进度.
session.upload_progress.freq[=1%] 更新进度的频率(已经处理的字节数), 也支持百分比表示’%’.
session.upload_progress.min_freq[=1.0] 更新进度的时间间隔(秒)
代码实现
html
<form id="upload-form" action="upload.php" method="post" enctype="multipart/form-data" target="hidden_iframe">
<input type="hidden" name="PHP_SESSION_UPLOAD_PROGRESS" value="test" />
<input type="file" name="fileToUpload" id="fileToUpload">
<input type="submit" value="Upload" name="submit">
</form>
<iframe id="hidden_iframe" name="hidden_iframe" src="about:blank" style="display:none;"></iframe>
<div id="progress" style="margin-top: 50px;display:block;font-size: 20px">0%</div>
js
<script type="text/javascript">
function fetch_progress() {
$.get('progress.php', {'PHP_SESSION_UPLOAD_PROGRESS': 'test'}, function (result) {
console.log(result);
var progress = parseInt(result.data);
$('#progress ').html(progress + '%');
if (progress < 100) {
setTimeout('fetch_progress()', 1000);
} else {
$('#progress .label').html('完成!');
}
}, 'json');
}
$('#upload-form').submit(function () {
$('#progress').show();
setTimeout('fetch_progress()', 1000);
});
</script>
progress.php
session_start();
$i = ini_get('session.upload_progress.name');
$key = ini_get("session.upload_progress.prefix") . $_GET[$i];
$outputData['name'] = $i;
if (!empty($_SESSION[$key])) {
$current = $_SESSION[$key]["bytes_processed"];
$total = $_SESSION[$key]["content_length"];
header_remove();
header('Content-Type: application/json; charset=utf-8');
$outputData['data'] = $current < $total ? ceil($current / $total * 100) : 100;
echo json_encode($outputData);
} else {
$outputData['data'] = 100;
echo json_encode($outputData);
}
Session 上传进度:http://php.net/manual/zh/session.upload-progress.php
如上例子只针对php5.4及以上版本,低于5.4版本请参看:http://www.cnblogs.com/y0umer/archive/2011/08/19/2809614.html