Thursday, February 26, 2009

php 文件上传进度条的实现

由于php5.2的改进,现在已经可以
有如下几个文件:
progress.php(上传主文件,生成独特的ID等,框架)
target.php(处理上传文件的脚本)
upload.php(生成上传文件对话框)
getprogress.php(获得上传文件的进度信息)
style.css(控制页面外观)
jqury.js(好用的js框架)
progress.js

upload.php生成上传框架



1 <?php

2 $id = $_GET['id'];

3 ?>

4 <form enctype="multipart/form-data" id="upload_form" action="target.php" method="POST">

5 <input type="hidden" name="APC_UPLOAD_PROGRESS" id="progress_key" value="<?php echo $id; ?>" />

6 <input type="file" id="test_file" name="test_file" /><br />

7 <input type="submit" value="Upload!" onclick="window.parent.startProgress(); return true;" />

8 </form>



target.php

1 <?php

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

3 move_uploaded_file($_FILES['test_file']['tmp_name'], "/tmp/{$_FILES['test_file']['name']}");

4 echo "<p>File uploaded. Thank you!</p>";

5 }

6 ?>



progress.php



1 <?php

2 $id = uniqid("");

3 ?>

4 <html>

5 <head><title>Upload Example</title></head>

6 <style type="text/css"> @import url("style.css"); </style>

7 <body>

8 <iframe id="theframe" name="theframe" src="upload.php?id=<?php echo ($id); ?>" style="border:none;height:1pppx;width:400px;" >

9 </iframe>

10 <br /><br />

11 <div id="progressouter">

12 <div id="progressinner">

13 </div>

14 </div>

15 <script type="text/javascript">

16 function getProgress() {

17 $.get("getprogress.php?progress_key=<?php echo($id); ?>",

18 function(percent) {

19 console.log(percent);

20 document.getElementById("progressinner").style.width = percent + "%";

21 if (percent < 100) {

22 setTimeout("getProgress()",100);

23 }

24 });

25 }

26 function startProgress() {

27 document.getElementById("progressouter").style.display="block";

28 setTimeout("getProgress()",100);

29 }

30

31 </script>

32 <script src="jquery.js" type="text/javascript"></script>

33 <script src="progress.js" type="text/javascript"></script>

34 </body>

35 </html>




getprogress.php



1 <?php

2 if (isset($_GET['progress_key'])) {

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

4 echo $status['current'] / $status['total'] * 100;

5 }

6 ?>




style.css



1 #progressouter {

2 height:20px;

3 border:1px solid #ccc;

4 -moz-border-radius:4px;

5 display:none;

6 width:500px;

7 }

8 #progressinner {

9 position:relative;

10 -moz-border-radius:4px;

11 height:20px;

12 width:0%;

13 background:transparent url('bg.png') repeat-x left 50%;

14 }




jquery.js(www.jquery.com下载)
bg.png



原文地址:http://www.ibm.com/developerworks/cn/opensource/os-php-v525/

No comments:

Labels

关于我

海淀, 北京, China