分享好友 编程语言首页 频道列表

php实现文件上传进度条

PHP教程  2023-02-09 10:000

 在PHP5.4以前, 我们可以通过APC提供的功能来实现. 或者使用PECL扩展uploadprogress来实现.

虽然说, 它们能很好的解决现在的问题, 但是也有很明显的不足:

  • 1. 他们都需要额外安装(我们并没有打算把APC加入PHP5.4)
  • 2. 它们都使用本地机制来存储这些信息, APC使用共享内存, 而uploadprogress使用文件系统(不考虑NFS), 这在多台前端机的时候会造成麻烦.



程序需要php的apc模块的支持,关键点就是在上传的form里添加一个hidden的inpu标签,里面要有name为

APC_UPLOAD_PROGRESS的属性,value值为一个随机数一遍多个人上传。

 

apc模块的安装方法是,下载php_apc.dll放到ext文件夹下,在php.ini文件里添加

upload_max_filesize =100M
      apc.rfc1867 = on
      apc.max_file_size = 100M

extension=php_apc.dll

然后测试配置是否成功:
if(apc_fetch)

{echo "apc is working"}

else{echo "apc is not supported!";}

 

 

 

运行效果截图

php实现文件上传进度条

下面是源码

1 前台页面:

Html代码  php实现文件上传进度条
  1. <html>  
  2. <title>PHP+Ajax带进度条文件上传</title>  
  3. <head>  
  4. <style type="text/css">  
  5. #progress{  
  6. border:2px red solid;  
  7. width:200px;  
  8. height:20px;  
  9. display:none;  
  10. }  
  11.   
  12. #pecent{  
  13. background-color:green;  
  14. display:block;  
  15. width:0px;  
  16. height:20px;  
  17. color:yellow;  
  18. }  
  19. </style>  
  20. </head>  
  21. <body>  
  22.     <iframe style="display:none" name="ifm"></iframe>  
  23.       <form enctype="multipart/form-data" method="POST" action="upload.php" target="ifm" name="myform">  
  24.       <input type="hidden" name="APC_UPLOAD_PROGRESS" id="remark" >  
  25.       <input type="file" name="upfile"/>  
  26.       <input type="submit" value="上传" name="sub"/>  
  27.       </form>  
  28.       <div id="progress" class="before"><span id="pecent"></span></div>  
  29.   
  30. <script type="text/javascript">  
  31. (function(){  
  32.     function addEvent( node, type, listener ) {  
  33.     if (node.addEventListener) {  
  34.         // W3C method  
  35.         node.addEventListener( type, listener, false );  
  36.         return true;  
  37.     } else if(node.attachEvent) {  
  38.         // MSIE method  
  39.         node['e'+type+listener] = listener;  
  40.         node[type+listener] = function(){node['e'+type+listener]( window.event );}  
  41.         node.attachEvent( 'on'+type, node[type+listener] );  
  42.         return true;  
  43.     }  
  44.     // Didn't have either so return false  
  45.     return false;  
  46.     };  
  47.     var submit=document.forms["myform"];  
  48.     addEvent(submit,'submit',startUpload);  
  49.     var begin;  
  50.     var request;  
  51.     var rdm;  
  52.     var pec=document.getElementById("pecent");  
  53.     function startUpload()  
  54.     {  
  55.         rdm=Math.floor(Math.random()*100000000);  
  56.         document.getElementById('remark').setAttribute('value',rdm);  
  57.         document.getElementById("progress").style['display']='block';  
  58.         //creatXmlHttpRequest();  
  59.         begin=setTimeout(doRequest,1000);  
  60.     };  
  61.     function creatXmlHttpRequest()  
  62.     {  
  63.         if(window.ActiveXObject)  
  64.         {request=new ActiveXObject("Microsoft.XMLHTTP")}  
  65.         else{request=new XMLHttpRequest();}  
  66.     };  
  67.     var count=0;  
  68.     function doRequest()  
  69.    {  
  70.        if(window.ActiveXObject)  
  71.         {request=new ActiveXObject("Microsoft.XMLHTTP");}  
  72.         else{request=new XMLHttpRequest();}  
  73.   
  74.        if(request!=null){  
  75.        request.onreadystatechange=handle;  
  76.        request.open("GET","upload.php?key="+rdm+"&sim=" + (++count),true);  
  77.        request.send();  
  78.        }  
  79.    };  
  80.         function handle()  
  81.         {  
  82.             if(request.readyState==4&&request.status==200)  
  83.             {  
  84.                 //接受服务器数据  
  85.                 var prgs=eval("(" +  request.responseText + ")");  
  86.                 //var prgs=request.responseText;  
  87.                 var cur=parseInt(prgs.current);  
  88.                 var total=parseInt(prgs.total);  
  89.                 var pecentIs=Math.round(cur/total*100);  
  90.                 pec.innerHTML=pecentIs.toString()+"%";  
  91.                 if(100==pecentIs)  
  92.                 {  
  93.                     pec.style['width']="200px";  
  94.                     clearTimeout(begin);  
  95.                 }else{  
  96.                     begin=setTimeout(doRequest,1000);  
  97.                     //alert(pecentIs);  
  98.                     pec.style['width']=pecentIs*2;  
  99.                 }  
  100.             }  
  101.         };  
  102.     })();  
  103.     </script>  
  104.     </body>  
  105. </html>  

 

2后台upload.php文件代码:

Php代码  php实现文件上传进度条
  1. <?php  
  2. /* 
  3.  * Created on 2010-4-16 
  4.  * 
  5.  * To change the template for this generated file go to 
  6.  * Window - Preferences - PHPeclipse - PHP - Code Templates 
  7.  */  
  8.  if ($_SERVER['REQUEST_METHOD'] == 'POST'){  
  9. $myfile=$_FILES['upfile'];  
  10. echo $myfile['size'];  
  11. echo $myfile['size'];  
  12. print_r($myfile);  
  13. $tempf=$myfile['tmp_name'];  
  14. $name=$myfile['name'];  
  15. move_uploaded_file($tempf,'up/'.$name);}  
  16.   
  17. if(isset($_GET['key']))  
  18. {  
  19.     //header('Content-Type:application/json; charset=utf-8' ) ;  
  20.     // Retrieve the status using the getStatus() function below  
  21.     //echo json_encode(getStatusAPC());  
  22.     echo json_encode(getStatusAPC());  
  23. }  
  24. function getStatusAPC()  
  25. {  
  26.     $response=false;  
  27.     if($status = apc_fetch('upload_'.$_GET['key'])) {  
  28.           
  29.         $response=apc_fetch('upload_'.$_GET['key']);  
  30.           
  31.     }  
  32.     return $response;  
  33. }  
  34.   
  35. ?>  

 问题总结:

1,使用setTimeout嵌套和setInterval有区别,用前者效果较好,用后者的话由于请求和返回的时间比较随机,时间间隔把握不好的话,程序会比较混乱,结果往往不正确。

2.发送Ajax请求时每次都要重新实例化xmlhttprequest对象而不能用上次实例化的,否则程序在ie下无法执行,在火狐下可以运行

 

查看更多关于【PHP教程】的文章

展开全文
相关推荐
反对 0
举报 0
评论 0
图文资讯
热门推荐
优选好物
更多热点专题
更多推荐文章
nginx和php-fpm 是使用 tcp socket 还是 unix socket ?
tcp socket允许通过网络进程之间的通信,也可以通过loopback进行本地进程之间通信。unix socket允许在本地运行的进程之间进行通信。分析从上面的图片可以看,unix socket减少了不必要的tcp开销,而tcp需要经过loopback,还要申请临时端口和tcp相关资源。但是

0评论2023-03-08437

PHP基于elasticsearch全文搜索引擎的开发 php使用es搜索引擎
1.概述:全文搜索属于最常见的需求,开源的 Elasticsearch (以下简称 Elastic)是目前全文搜索引擎的首选。Elastic 的底层是开源库 Lucene。但是,你没法直接用 Lucene,必须自己写代码去调用它的接口。Elastic 是 Lucene 的封装,提供了 REST API 的操作接

0评论2023-02-09676

php视图操作
一、视图的基本介绍         视图是虚拟的表。与包含数据的表不一样,视图只包含使用时动态检索数据的查询。        使用视图需要MySQL5及以后的版本支持。        下面是视图的一些常见应用:        重用SQL语句;        简化复杂的S

0评论2023-02-09320

php使用时间戳保存时间的意义 PHP获取时间戳
时间戳记录的是格林尼治时间,使用date格式化的时候会根据你程序设置的不同时区显示不同的时间。如果使用具体时间,则还需要进行多一步转换。

0评论2023-02-09607

PHP 获取提交表单数据方法
PHP $_GET 和 $_POST变量是用来获取表单中的信息的,比如用户输入的信息。PHP表单操作在我们处理HTML表单和PHP表单时,我们要记住的重要一点是:HTML页面中的任何一个表单元素都可以自动的用于PHP脚本:表单举例: htmlbodyform action="welcome.php" method

0评论2023-02-09522

php中file_get_contents与curl的区别 php get file content
做微信开发的时候,项目中需要用PHP去请求微信相关接口。刚开始使用的是file_get_contents这个函数,后来听朋友说最好用curl。自己尝试了下,也能成功请求微信的接口。这两个有什么区别呢?抱着好奇心查阅了相关资料后,才知道他们之间确实有很大的不同。1.fo

0评论2023-02-09764

PHP与java接口对接使用json格式请求 php接收post数据json
PHP与java接口对接使用json格式请求$datajson = json_encode($param);$myheader= array('Content-Type: application/json; charset=utf-8','Content-Length: ' . strlen($datajson));$result = http_curl($url, 'xml', $datajson, 6, FALSE, ''

0评论2023-02-09566

PHP会员找回密码功能的简单实现 php密码登录验证
文章来自:博客http://www.jb51.net/article/91944.htm 设置思路1、用户注册时需要提供一个E-MAIL邮箱,目的就是用该邮箱找回密码。2、当用户忘记密码或用户名时,点击登录页面的“找回密码”超链接,打开表单,并输入注册用的E-MAIL邮箱,提交。3、系统通过

0评论2023-02-09488

php 判断一个变量是否是合法的json
1.场景api验证前端json 类型字段合法性2.分析官网3.解决function json_validate($string) {if (is_string($string)) {@json_decode($string);return (json_last_error() === JSON_ERROR_NONE);}return false;} 

0评论2023-02-09411

Apache 的 php.ini 配置文件详解
[root@taokey ~]# grep -v ";" /application/php/lib/php.ini  [PHP]  engine = On  ——→  是否启用 PHP 解析引擎  short_open_tag = Off    ——→  是否使用简介标志  asp_tags = Off  ——→  不允许 asp 类标志  precision = 14  —

0评论2023-02-09716

PHP的几种输出方式 php输出格式
请写出echo、print_r、print、var_dump 、die之间的区别   echo  只能输出字符串等单一数据 不能输出数据类型 不能输出数组等多种数据   print()  只能输出字符串等单一数据 不能输出数据类型 不能输出数组等多种数据有返回值true/false   print_r()

0评论2023-02-09753

建设银行网上银行MD5withRSA php版
1. 首先通过java程序将建设银行的公钥串转成pem格式并写入文件SignTest.java是运行程序, RSASig.java是建设银行签名算法类, bcprov-jdk15-145.jar是PEMWriter类库 2. php程序做签名验证?php$data = "POSID=000000000BRANCHID=330000000ORDERID=2004010061P

0评论2023-02-09605

php服务器删除浏览器cookie php清除浏览器缓存
一、设置cookie的过期时间//将过期时间设为一小时前setcookie("TestCookie", "", time() - 3600);setcookie("TestCookie", "", time() - 3600, "/~rasmus/", ".utoronto.ca", 1);二、设置cookie的值为空setcookie($cookiename, ''

0评论2023-02-09874

Docker-用LaraDock搭建PHP环境 docker搭建php开发环境
简介LaraDock 致力于简化创建开发环境过程,能够帮助我们在 Docker 上快速搭建 PHP 开发环境。 它预装了 Docker 镜像,为我们提供了一站式的开发环境,而不需要再去在本地机器安装 PHP、Nginx、MySQL 以及其他很多开发过程中需要的软件。特点:在 PHP 版本:7

0评论2023-02-09851

更多推荐