我们通过安装 PECL 扩展并向窗体添加一个简单的 AJAX 回调来实现这一点非常简单:pecl-uploadprogress
生成上传密钥:
$upload_id = genUploadKey();
function genUploadKey ($length = 11) {
$charset = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
for ($i=0; $i < $length; $i++)
$key .= $charset[(mt_rand(0,(strlen($charset)-1)))];
return $key;
}
创建一个 AJAX 回调处理程序(例如 uploadprogress.php):
extract($_REQUEST);
// servlet that handles uploadprogress requests:
if ($upload_id) {
$data = uploadprogress_get_info($upload_id);
if (!$data)
$data['error'] = 'upload id not found';
else {
$avg_kb = $data['speed_average'] / 1024;
if ($avg_kb<100)
$avg_kb = round($avg_kb,1);
else if ($avg_kb<10)
$avg_kb = round($avg_kb,2);
else $avg_kb = round($avg_kb);
// two custom server calculations added to return data object:
$data['kb_average'] = $avg_kb;
$data['kb_uploaded'] = round($data['bytes_uploaded'] /1024);
}
echo json_encode($data);
exit;
}
// display on completion of upload:
if ($UPLOAD_IDENTIFIER) {
...
下载jQuery和jQuery.uploadprogress库(其中还包括上面的代码段)并与您的表单集成:
<script type="text/javascript" src="jquery.min.js"></script>
<script type="text/javascript" src="jquery.uploadprogress.0.3.js"></script>
<script type="text/javascript">
jQuery(function () {
// apply uploadProgress plugin to form element
// with debug mode and array of data fields to publish to readout:
jQuery('#upload_form').uploadProgress({
progressURL:'uploadprogress.php',
displayFields : ['kb_uploaded','kb_average','est_sec'],
start: function() {
$('.upload-progress').show();
},
success: function() {
$('.upload-progress').hide();
jQuery(this).get(0).reset();
}
});
});
</script>
将其添加到您的上传表单:
<input name="UPLOAD_IDENTIFIER" type="hidden" value="$upload_id" />
这应该可以解决问题。这是从我们的代码库中提取的,可能无法开箱即用。但它应该告诉你这个想法。