search
HomeBackend DevelopmentPHP TutorialPHP利用APC模块实现大文件上传进度条的方法_PHP

php 大文件带进度的上传,一直是一个令php程序员很苦恼的问题。查询baidu 、Google ,大体做带进度的上传方式为:flash+php,socket,apc+php等,下面我介绍了apc +php+ajax制作的带进度的上传,并贴出源码,希望对大家有用。
Alternative PHP Cache(APC)是 PHP 的一个免费公开的优化代码缓存。它用来提供免费,公开并且强健的架构来缓存和优化 PHP 的中间代码。 

在使用apc时候,先必须使用安装apc 模块。
第一步:下载php_apc.dll

第二步:让php.ini支持apc扩展模块。
将php_apc.dll放入你的ext目录,然后打开php.ini 加入:
     extension=php_apc.dll
     apc.rfc1867 = on
     apc.max_file_size = 100M
     upload_max_filesize = 100M
     post_max_size = 100M
     //以上参数可自己定义 

第三步:检查是否支持PHP APC

 if (function_exists('apc_fetch')) {
 echo 'it surpport apc model!';
 } else {
 echo "it's not support apc model!";
 }
 ?>

下面进入正题:
原理:通过APC 模块,用ajas从缓存中读取上传的进度。详见:
 index.php 

<&#63;php
 $unid=uniqid("");//确定唯一标致,实现多人同时上传
&#63;>
<div class="userinput2">
 <div id="captions">先将你要上传的软件上传服务器,上传时请耐心等候...<span class="style1"><br />
 </span>
 <script type="text/javascript" >
  var xmlHttp;
 var proNum=0;
 var loop=0;
 //初始化xmlHttp
 function createxml(){
 var xmlHttp;
 if(window.XMLHttpRequest){
 xmlHttp=new XMLHttpRequest();
 }else{
 xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
 }
 return xmlHttp;
 }
 xmlHttp=createxml();
 //ajas操作
 function sendURL() {
  var url="getprogress.php&#63;progress_key=<&#63;php echo $unid;&#63;>";
  xmlHttp.open("GET",url,false);
  if (window.navigator.userAgent.indexOf("Firefox")>=1){
  //如果是firefox3.0
  xmlHttp.send("progress_key=<&#63;php echo $unid;&#63;>");
  if(xmlHttp.status==200) doHttpReadyStateChange();
 
  }else{
  xmlHttp.onreadystatechange = doHttpReadyStateChange;
  xmlHttp.send("progress_key=<&#63;php echo $unid;&#63;>");
  }
 }
 //回调函数
 function doHttpReadyStateChange() {
  if (xmlHttp.readyState== 4){
  proNum=parseInt(xmlHttp.responseText);
  //alert(proNum);
  document.getElementByIdx_x("progressinner").style.width = proNum+"%";
  document.getElementByIdx_x("showNum").innerHTML = proNum+"%";
  if ( proNum < 100){
  setTimeout("sendURL()", 200);
  }else{
  //上传成功后,还不能及时得到信息。还希望高人指点
  document.getElementByIdx_x("progressouter").style.display="none";
  document.getElementByIdx_x("progressinner").style.display="none";
  document.getElementByIdx_x("showNum").style.display="none";
  document.getElementByIdx_x("theframe").style.display="none";
  document.getElementByIdx_x("link2").style.display="block";
  }
 
  }
 }
 function startProgress(){
  document.getElementByIdx_x("progressouter").style.display="block";
  setTimeout("sendURL()", 200);
 }
 function newsofturl(text){
  document.getElementByIdx_x("link2").style.display="block";
  document.getElementByIdx_x("link2").value=text;
 }
 </script>
 <iframe id="theframe" name="theframe" src="softupload.php&#63;id=<&#63;php echo($unid); &#63;>" style="border: 0; height: 80px; width: 400px; " frameborder="0" scrolling="no" > </iframe>
 <input name="linkdefult" type="hidden" id="linkdefult" value="0" />
 <br />
 <div id="link2" style="display:none;" > <font size=2>上传成功!    文件大小为:
  <input type="text" name="filesize" id="filesize" style="width:50px;"/>
  </font><br>
  <br>
  <font size=2>文件下载地址为:</font><br />
  <input type=text name='link' id='link' style='width:380px;' />
 </div>
 <br/>
 <div id="progressouter" style="width: 500px; height: 20px; border: 1px solid #000000; display:none;">
  <div id="progressinner" style="position: relative; height: 20px; background-color: #333333; width: 0%; "></div>
 </div>
 <div id='showNum' style="font-size:12px; color:#333333"></div>
 </div>
</div>
 

softupload.php

<&#63;php
 $id = $_GET['id'];
&#63;>
<script language="javascript">
//Trim the input text
function Trim(input)
{
 var lre = /^\s*/;
 var rre = /\s*$/;
 input = input.replace(lre, "");
 input = input.replace(rre, "");
 return input;
 }
function CheckForTestFile()
 {
  var file = document.getElementByIdx_x('Softfile');
  var fileName=file.value; 
  //Checking for file browsed or not
  if (Trim(fileName) =='' )
  {
  alert("请为上传选择一个文件!!!");
  file.focus();
  return false;
  }
 //Setting the extension array for diff. type of text files
 var extArray = new Array(".rar", ".zip", ".exe", ".gz"); 
 //getting the file name
 while (fileName.indexOf("\") != -1)
  fileName = fileName.slice(fileName.indexOf("\") + 1);

 //Getting the file extension   
 var ext = fileName.slice(fileName.indexOf(".")).toLowerCase();
 for (var i = 0; i < extArray.length; i++)
 {
  if (extArray[i] == ext)
  {
  window.parent.startProgress(); return true;
  }
 }
  alert("正确的文件格式为" + (extArray.join(" ")) + "\n请选择一个新的 " + "文件提交上传.");
  file.focus();
  return false;  
 } 
</script> <meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<form enctype="multipart/form-data" id="upload_form" action="target.php" method="POST">
<input type="hidden" name="APC_UPLOAD_PROGRESS" id="progress_key" value="<&#63;php echo $id&#63;>"/>
<table width="322" border="0" cellpadding="0" cellspacing="0" id="linkTable">

 <tr>
 <td >1.选择软件<br />

 <input name="Softfile" type="file" id="Softfile" /></td>
 <td ><br />
 <input name="submit" type="submit" onclick="return CheckForTestFile();" value="上传软件"/></td>
 </tr>
 </table>
</form>

target.php

<script language="javascript">
//将上传后的信息返还给父窗口
function chuanzhi(){
parent.document.getElementByIdx_x('filesize').value=document.getElementByIdx_x('size').value;
parent.document.getElementByIdx_x('link').value=document.getElementByIdx_x('newsoftdir').value;
parent.document.getElementByIdx_x('linkdefult').value=1;
}
</script>
<body >
<&#63;php
//header('Content-Type:text/html;charset=gb2312');
define('SOFTDIR', "./upload/");  //上传后路径
define('HTTPSOFTDIR', "http://www.mysite.com/"); //服务器的路径

//判断上传软件后缀名是否允许
function isSoftExt($extension) {
 $ext = array('exe', 'rar', 'zip','gz');
 return in_array($extension, $ext) &#63; true : false;
}
if($_SERVER['REQUEST_METHOD']=='POST'){
$errors['0'] = true;
$errors['1'] = '请选择上传的软件图片';
$errors['2'] = '上传软件图片失败';
$errors['3'] = '上传软件图片失败';
$daytime = date('Y-m-d-h-m-s');
$timename=str_replace("-","",$daytime); //取得当天的日期时间


 //检查软件是否是正常上传的
 if(!is_uploaded_file($_FILES['Softfile']['tmp_name'])) {
 echo "<script>alert('非正常上传!');history.back();</script>";
 exit;
 }
 $extension = pathinfo($_FILES['Softfile']['name'], PATHINFO_EXTENSION);
 $filename = $timename."_".$_FILES['Softfile']['name'];
 $tmpsize=$_FILES['Softfile']['size'];
 $msize=round($tmpsize/1048576 , 2) ."M";
 $ksize=round($tmpsize/1024 ,2). "K";
 $filesize =$tmpsize>1048576&#63;$msize:$ksize;
 //检查软件文件格式
 if(!isSoftExt($extension)) {
 echo "<script>alert('上传的软件格式有错误!');history.back();</script>";
 exit;
 } 
 //移动软件
 if(!move_uploaded_file($_FILES['Softfile']['tmp_name'], SOFTDIR. $filename)) {
 echo "<script>alert('移动软件出错!');history.back();</script>";
 exit;
 }else{
 echo "<font size=2>上传成功!    文件大小为:<input type=text id='size' value='$filesize'></font><br>";
 echo "<font size=2>文件下载地址为:</font><input type=text id='newsoftdir' value='".HTTPSOFTDIR.$filename."' style='width=380'>";
 }
}else
echo "请不要直接输入地址!";

&#63;>

getprogress.php

<&#63;php
//上传ajas获取进度页面
session_start();
if(isset($_GET['progress_key'])) {
 $status = apc_fetch('upload_'.$_GET['progress_key']);
 echo ($status['current']/$status['total'])*100;
}
echo 'APC_FILE='.APC_FILE;
&#63;>

本文为大家提供了一个php制作带进度上传文件的思路,可能还有一些欠缺的地方,希望大家进行补充,或者是再结合小编之前整理的文章进行学习,希望对大家的学习有所帮助。

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
The Continued Use of PHP: Reasons for Its EnduranceThe Continued Use of PHP: Reasons for Its EnduranceApr 19, 2025 am 12:23 AM

What’s still popular is the ease of use, flexibility and a strong ecosystem. 1) Ease of use and simple syntax make it the first choice for beginners. 2) Closely integrated with web development, excellent interaction with HTTP requests and database. 3) The huge ecosystem provides a wealth of tools and libraries. 4) Active community and open source nature adapts them to new needs and technology trends.

PHP and Python: Exploring Their Similarities and DifferencesPHP and Python: Exploring Their Similarities and DifferencesApr 19, 2025 am 12:21 AM

PHP and Python are both high-level programming languages ​​that are widely used in web development, data processing and automation tasks. 1.PHP is often used to build dynamic websites and content management systems, while Python is often used to build web frameworks and data science. 2.PHP uses echo to output content, Python uses print. 3. Both support object-oriented programming, but the syntax and keywords are different. 4. PHP supports weak type conversion, while Python is more stringent. 5. PHP performance optimization includes using OPcache and asynchronous programming, while Python uses cProfile and asynchronous programming.

PHP and Python: Different Paradigms ExplainedPHP and Python: Different Paradigms ExplainedApr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP and Python: A Deep Dive into Their HistoryPHP and Python: A Deep Dive into Their HistoryApr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Choosing Between PHP and Python: A GuideChoosing Between PHP and Python: A GuideApr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP and Frameworks: Modernizing the LanguagePHP and Frameworks: Modernizing the LanguageApr 18, 2025 am 12:14 AM

PHP remains important in the modernization process because it supports a large number of websites and applications and adapts to development needs through frameworks. 1.PHP7 improves performance and introduces new features. 2. Modern frameworks such as Laravel, Symfony and CodeIgniter simplify development and improve code quality. 3. Performance optimization and best practices further improve application efficiency.

PHP's Impact: Web Development and BeyondPHP's Impact: Web Development and BeyondApr 18, 2025 am 12:10 AM

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

How does PHP type hinting work, including scalar types, return types, union types, and nullable types?How does PHP type hinting work, including scalar types, return types, union types, and nullable types?Apr 17, 2025 am 12:25 AM

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values ​​and handle functions that may return null values.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools