PHP5.4以上版本,$_SESSION中内置了Upload progress,可以支持文件上传进度。
方法和apc扩展(参考:http://blog.feizhaojun.com/?p=22)差不多,只不过这里不用到扩展而是用到了php5.4内置的$_SESSION。
以下是一个示例,测试通过:
首先,示例中引用了jQuery.js,大家不要忘了,另外需要新建一个up的目录,存储上传文件。
文件1:index.php
[php]
<?php
header("Content-type: text/html; charset=utf-8");
session_start();
$id = uniqid("");
?>
<html>
<head>
<title>Upload Example</title>
<script src="jquery.js" type="text/javascript"></script>
<script type="text/javascript">
function getProgress(get_id){
$.get("getprogress.php?progress_key=<?php echo $id; ?>&get_id="+get_id,
function(result){
$("#progress").css({"width":parseInt(5*result)});
$("#percent").html(result+"%");
if (result < 100){
setTimeout("getProgress("+result+")",20);
}else{
$("#percent").html(result);
}
}
);
}
function startProgress(){
$("#progress_bar").css({"display":"block"});
//$("#theframe").css({"display":"none"});
setTimeout("getProgress()",20);
}
</script>
</head>
<body>
<div id="percent"></div>
<div id="progress_bar" style="width: 500px; height: 5px; border: 1px solid #e0e0e0;display:none;font-size:0;">
<div id="progress" style="position: relative; height: 5px; background-color: #0088ff; width: 0%; "></div>
</div>
<iframe id="theframe" name="theframe" src="upload.php?id=<?php echo($id) ?>" style="border: none; height: 200px; width: 100%;" ></iframe>
</body>
</html>
[/php]
文件2:upload.php
[php]
<?php
header("Content-type: text/html; charset=utf-8");
session_start();
if(isset($_GET['id'])){$id=$_GET['id'];}
?>
<html>
<body>
<?php
if($_SERVER['REQUEST_METHOD']=='POST') {
for($i=1;$i<2;$i++){
move_uploaded_file($_FILES["test_file".$i]["tmp_name"],"up/".time()."_".iconv("UTF-8","gb2312",$_FILES["test_file".$i]["name"]));
echo "<p>\"".$_FILES["test_file".$i]["name"]."\" upload successful!</p>";
}
}else{
?>
<form enctype="multipart/form-data" id="upload_form" action="upload.php" method="POST">
<input type="hidden" name="<?php echo ini_get("session.upload_progress.name"); ?>" id="progress_key" value="<?php echo $id; ?>" />
<?php for($i=1;$i<2;$i++){ ?>
<input type="file" id="test_file<?php echo $i; ?>" name="test_file<?php echo $i; ?>"/><br/>
<?php } ?>
<input onclick="window.parent.startProgress(); return true;" type="submit" value="Upload!"/>
</form>
<?php
}
?>
</body>
</html>
[/php]
文件3:getprogress.php
[php]
<?php
header("Content-type: text/html; charset=utf-8");
session_start();
//print_r($_SESSION["upload_progress_".$_GET['progress_key']]);
if(isset($_GET['progress_key'])){
$status = $_SESSION["upload_progress_".$_GET['progress_key']];
//print_r($status);
if($status["done"]){
echo 100;
}else{
echo number_format($status['bytes_processed']/$status['content_length']*100, 2, '.','');
}
}
?>
[/php]
您的赞助将会支持作者创作及本站运维
发表评论