核心提示:目前我知道的方法有两种,一种是使用PHP的创始人 Rasmus Lerdorf 写的APC扩展模块来实现,另外一种方法是使用PECL扩展模块uploadprogress实现。

目前我知道的方法有两种,一种是使用PHP的创始人 Rasmus Lerdorf 写的APC扩展模块来实现(http://pecl.php.net/package/apc),另外一种方法是使用PECL扩展模块uploadprogress实现(http://pecl.php.net/package/uploadprogress)我这里举两个分别实现的例子供参考,更灵活的应用根据自己需要来修改。

APC实现方法:

安装APC,参照官方文档安装,可以使用PECL模块安装方法快速简捷,这里不说明

配置php.ini,设置参数 apc.rfc1867=1 ,使APC支持上传进度条功能,在APC源码说明文档里面有说明

代码范例:


if ($_SERVER['REQUEST_METHOD'] == ‘POST‘) { //上传请求

$status = apc_fetch(‘upload_‘ . $_POST['APC_UPLOAD_PROGRESS']);

$status['done'] = 1;

echo json_encode($status); //输出给用户端页面里的ajax调用,相关文档请自己寻找

exit;

} elseif (isset($_GET['progress_key'])) { //读取上传进度

$status = apc_fetch(‘upload_‘.$_GET['progress_key']);

echo json_encode($status);

exit;

} else {

//其他代码,比如上传表单等

}

uploadprogress 模块实现方法:

使用PECL模块安装方法安装该模块

php.ini里面设置 uploadprogress.file.filename_template = “/tmp/upd_%s.txt”

代码范例:


if($_SERVER['REQUEST_METHOD']==‘POST‘) {

if (is_uploaded_file($_FILES['upfile']['tmp_name'])) {

$upload_dir = ‘your_path/‘;

$ext = strrchr($_FILES['video']['name'], ‘.‘);

$sessid = $_POST['UPLOAD_IDENTIFIER'] ;

$tmpfile = $upload_dir . $sessid;

$sessfile = $upload_dir . $sessid .$ext;

if (move_uploaded_file($_FILES['upfile']['tmp_name'],$tmpfile)) {

//上传成功

} else {

//上传失败

} else {

//上传错误


} elseif (!empty($_GET['sessid'])) {

header(“Expires: Mon, 26 Jul 1997 05:00:00 GMT“);

header(“Last-Modified: “ . gmdate(“D, d M Y H:i:s“) . “ GMT“);

header(“Cache-Control: no-store, no-cache, must-revalidate“);

header(“Cache-Control: post-check=0, pre-check=0“, false);

header(“Pragma: no-cache“);

header(“Content-Type:text/html;charset=UTF-8“);


$unique_id = $_GET['sessid'];

$uploadvalues = uploadprogress_get_info($unique_id);


if (is_array($uploadvalues)) {

echo json_encode($uploadvalues);

} else {

//读取进度失败,另外处理逻辑

}


} else {

//显示上传表单

}















这两天研究了下,PHP上传进度条的问题,就用了其中的一种方法:借用apc的扩展;

1.APC扩展库的安装(windows);

(1)首先下载php_apc.dll,然后再php.ini里配置:在扩展库后加(;extension=php_zip.dll)->

extension=php_apc.dll
apc.rfc1867=1
apc.cache_by_default    =Off   
apc.enable_cli       =Off   
apc.enabled       =On   
apc.file_update_protection =2   
apc.filters       =""
apc.gc_ttl       =3600
apc.max_file_size    =200M   
apc.num_files_hint    =1000
apc.optimization    =On   
apc.shm_segments    =1   
apc.shm_size       =30   
apc.slam_defense    =Off   
apc.stat       =On   
apc.ttl          =0   
apc.user_entries_hint    =100   
apc.user_ttl      

(2)把php_apc.dll复制到c盘windows文件夹下

(3)重启apache,测试有没安装成功!

if(function_exists("apc_fetch")){

echo "安装成功!";

}

else

{

echo "安装失败,请重新安装!";

}

2.把相关的代码贴上

(1)getprogress.php

<?php
session_start();
if(isset($_GET['progress_key'])) {
$status =apc_fetch('upload_'.$_GET['progress_key']);
echo ($status['current']/$status['total'])*100;
}

?>

(2)upload.php

<style type="text/css">
*{margin:0px;padding:0px;}
</style>
<?php
   $id = $_GET['id'];
   if($_GET["add"]=="ok")
   {
    echo "上传成功!";
   }
   else{
?>
<form enctype="multipart/form-data" id="upload_form" action="target.php" name="upload_form" method="POST">
<input type="hidden" name="APC_UPLOAD_PROGRESS" id="progress_key" value="<?php echo $id?>"/>
<input type="file" id="test_file" name="test_file" οnchange="window.parent.startProgress();" style="width:190px;height:20px; background-color:gray;"/><br/>
</form>
<?php
}
?>

(3)progress.php

<?php
   $id = md5(uniqid(rand(), true));
?>
<html>
<head><title>php文件上传进度</title></head>
<body>
<script type="text/javascript">
var xmlHttp;
var proNum=0;
var loop=0;
var Try = {
these: function() {
    var returnValue;
    for (var i = 0; i < arguments.length; i++) {
      var lambda = arguments[i];
      try {
        returnValue = lambda();
        break;
      }
catch (e) {}
    }
    return returnValue;
}
}

function createXHR(){
return Try.these(
      function() {return new XMLHttpRequest()},
      function() {return new ActiveXObject('Msxml2.XMLHTTP')},
      function() {return new ActiveXObject('Microsoft.XMLHTTP')}
    ) || false;
}

var xmlHttp;

function sendURL() {
    xmlHttp=createXHR();
    var url="getprogress.php?progress_key=<?php echo $id;?>";
    xmlHttp.onreadystatechange=doHttpReadyStateChange;
    xmlHttp.open("GET",url,true);
    xmlHttp.send(null);  
}
function doHttpReadyStateChange() {
   if (xmlHttp.readyState == 4){
proNum=parseInt(xmlHttp.responseText);
document.getElementByIdx_x("progressinner").style.width = proNum+"%";
document.getElementByIdx_x("showNum").innerHTML = proNum+"%";
if (proNum<100){
   setTimeout("getProgress()",500);
}
else
{
   window.theframe.location.href='upload.php?add=ok';
}
}
}

function getProgress(){
loop++;
document.getElementByIdx_x("showNum2").innerHTML = loop;
sendURL();
}
function startProgress(){
    document.getElementByIdx_x("progressouter").style.display="block";
    setTimeout("getProgress()",500);
window.theframe.upload_form.submit();
}
</script>
<iframe id="theframe" name="theframe" src="upload.php?id=<?php echo($id); ?>" style=" height:20px; width: 190px;" frameborder="0" scrolling="no">
</iframe>
<div id="progressouter" style="font-size:0px;width:300px;height:5px;border: 1px solid red;display:none;">
<div id="progressinner" style="font-size:0px;position: relative; height:5px; background-color: purple; width:0%;">
</div>
</div><div id='showNum'></div><br>
<div id='showNum2'></div>
</body>
</html>
(4)target.php

<?php
set_time_limit(600);
if($_SERVER['REQUEST_METHOD']=='POST') {
move_uploaded_file($_FILES["test_file"]["tmp_name"],dirname($_SERVER['SCRIPT_FILENAME'])."/upload/" . $_FILES["test_file"]["name"]);//UploadTemp文件夹位于此脚本相同目录下

}

?>

3.打开progress.php进行测试,可以把源码修改成更好的!