介绍
PHP文档非常详细,它说:
当上传正在进行时,在$_SESSION超全局变量中将可用上传进度,并且当POST一个与session.upload_progress.name INI设置相同的变量名称时,PHP会弹出一个数组到$_SESSION中,其中索引是session.upload_progress.prefix和session.upload_progress.name INI选项的连接值。通常通过读取这些INI设置来检索键。
您需要的所有信息都已经在PHP会话命名中了:
- start_time
- content_length
- bytes_processed
- 文件信息(支持多个)
您只需要提取此信息并在HTML表单中显示即可。
基本示例
a.html
<link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/themes/base/jquery-ui.css"
rel="stylesheet" type="text/css" />
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.min.js"></script>
<script type="text/javascript">
var intval = null;
var percentage = 0 ;
function startMonitor() {
$.getJSON('b.php',
function (data) {
if (data) {
percentage = Math.round((data.bytes_processed / data.content_length) * 100);
$("#progressbar").progressbar({value: percentage});
$('#progress-txt').html('Uploading ' + percentage + '%');
}
if(!data || percentage == 100){
$('#progress-txt').html('Complete');
stopInterval();
}
});
}
function startInterval() {
if (intval == null) {
intval = window.setInterval(function () {startMonitor()}, 200)
} else {
stopInterval()
}
}
function stopInterval() {
if (intval != null) {
window.clearInterval(intval)
intval = null;
$("#progressbar").hide();
$('#progress-txt').html('Complete');
}
}
startInterval();
</script>
b.php
session_start();
header('Content-type: application/json');
echo json_encode($_SESSION["upload_progress_upload"]);
使用PHP会话上传进度的示例
这是一份更优化的版本,源自PHP会话上传进度
JavaScript
$('#fileupload').bind('fileuploadsend', function (e, data) {
if (data.dataType.substr(0, 6) === 'iframe') {
var progressObj = {
name: 'PHP_SESSION_UPLOAD_PROGRESS',
value: (new Date()).getTime()
};
data.formData.push(progressObj);
data.context.data('interval', setInterval(function () {
$.get('progress.php', $.param([progressObj]), function (result) {
e = document.createEvent('Event');
e.initEvent('progress', false, true);
$.extend(e, result);
$('#fileupload').data('fileupload')._onProgress(e, data);
}, 'json');
}, 1000));
}
}).bind('fileuploadalways', function (e, data) {
clearInterval(data.context.data('interval'));
});
进度.php
$s = $_SESSION['upload_progress_'.intval($_GET['PHP_SESSION_UPLOAD_PROGRESS'])];
$progress = array(
'lengthComputable' => true,
'loaded' => $s['bytes_processed'],
'total' => $s['content_length']
);
echo json_encode($progress);
其他示例