7天入门php-文件上传进度

获取文件上传进度的方法很多,该文介绍的是使用session.upload_progress,基于PHP 5.4以上版本的方法。

【1】文件php.ini 配置

根据实际情况进行设置

session.upload_progress.enabled[=1] : 是否启用上传进度报告(默认开启)
session.upload_progress.cleanup[=1] : 是否在上传完成后及时删除进度数据(默认开启, 推荐开启).
session.upload_progress.prefix[=upload_progress_] : 进度数据将存储在_SESSION[session.upload_progress.prefix . _POST[session.upload_progress.name]]
session.upload_progress.name[=PHP_SESSION_UPLOAD_PROGRESS] : 如果_POST[session.upload_progress.name]没有被设置, 则不会报告进度.
session.upload_progress.freq[=1%] : 更新进度的频率(已经处理的字节数), 也支持百分比表示’%’.
session.upload_progress.min_freq[=1.0] : 更新进度的时间间隔(秒级)


;允许客户端单个POST请求发送的最大数据 M
post_max_size=2048M

;接受所有数据到开始执行脚本的最大时间 S
max_input_time=60

;脚本的最大执行时间 S
max_execution_time=0

;是否开启文件上传功能
file_uploads = On

;文件上传的临时目录
upload_tmp_dir="C:\xampp\tmp"

;允许单个请求上传的最大文件大小 M
upload_max_filesize = 2048M

;允许单个POST请求同时上传的最大文件数量
max_file_uploads = 20




【2】 _FILES变量简介

[php]  view plain  copy
 print ? 在CODE上查看代码片 派生到我的代码片
  1. $_FILES["file"]["name"] - 被上传文件的名称  
  2. $_FILES["file"]["type"] - 被上传文件的类型  
  3. $_FILES["file"]["size"] - 被上传文件的大小,以字节计  
  4. $_FILES["file"]["tmp_name"] - 存储在服务器的文件的临时副本的名称  
  5. $_FILES["file"]["error"] - 由文件上传导致的错误代码  


【3】代码

文件上传表单

      设置session.upload_progress.name key的值

[php]  view plain  copy
 print ? 在CODE上查看代码片 派生到我的代码片
  1. <?php  
  2. if (version_compare(phpversion(), '5.4.0''<'))  
  3.     exit('ERROR: Your PHP version is ' . phpversion() . ' but this script requires PHP 5.4.0 or higher.');  
  4.   
  5. if (!intval(ini_get('session.upload_progress.enabled')))  
  6.     exit('session.upload_progress.enabled is not enabled, please activate it in your PHP config file to use this script.');  
  7.   
  8. require_once ("upload.class.php");  
  9. ?>  
  10.   
  11. <!doctype html>  
  12. <html>  
  13. <head>  
  14. <meta charset="utf-8">  
  15. </head>  
  16. <body>  
  17. <form id="upload-form" action="upload.php" method="POST" enctype="multipart/form-data">  
  18.  <!--设置session.upload_progress.name Key的值-->  
  19.  <input type="hidden"  
  20.   name="<?php echo ini_get("session.upload_progress.name"); ?>" value="<?php echo CUpload::UPLOAD_PROGRESS_PREFIX; ?>" />  
  21.  <table>  
  22.  <tr>  
  23.  <td><input name="file1[]" type="file" align="right"/></td>  
  24.  <td><input type="submit" name="Submit" value="上传"/></td>  
  25.  </tr>  
  26.  </table>   
  27. </form>  
  28. </body>  
  29. </html>  

文件上传处理类

[php]  view plain  copy
 print ? 在CODE上查看代码片 派生到我的代码片
  1. <?php  
  2. class CUpload  
  3. {  
  4.     const   UPLOAD_PROGRESS_PREFIX = 'progress_bar';  
  5.     private $_sMsg,  $_sUploadDir,  $_sProgressKey;  
  6.   
  7.     // The short array syntax (only for PHP 5.4.0 and higher)  
  8.     private $_aErrFile = [  
  9.          UPLOAD_ERR_OK         => 'There is no error, the file uploaded with success.',  
  10.          UPLOAD_ERR_INI_SIZE   => 'The uploaded file exceeds the upload_max_filesize directive in php.ini.',  
  11.          UPLOAD_ERR_FORM_SIZE  => 'The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form.',  
  12.          UPLOAD_ERR_PARTIAL    => 'The uploaded file was only partially uploaded.',  
  13.          UPLOAD_ERR_NO_FILE    => 'No file was uploaded.',  
  14.          UPLOAD_ERR_NO_TMP_DIR => 'Missing a temporary folder.',  
  15.          UPLOAD_ERR_CANT_WRITE => 'Failed to write file to disk.',  
  16.          UPLOAD_ERR_EXTENSION  => 'A PHP extension stopped the file upload.'  
  17.     ];  
  18.   
  19.     public function __construct()  
  20.     {  
  21.         // Session initialization  
  22.         if ('' === session_id()) session_start();  
  23.   
  24.         $this->_sUploadDir = 'uploads/';  
  25.         $this->_sProgressKey = strtolower(ini_get('session.upload_progress.prefix') . static::UPLOAD_PROGRESS_PREFIX);  
  26.     }     
  27.       
  28.     public function __destruct()  
  29.     {  
  30.         if ('' !== session_id())  
  31.         {  
  32.             $_SESSION = array();     
  33.             session_destroy();  
  34.         }  
  35.     }  
  36.   
  37.     /** 
  38.      * @return object this 
  39.      */  
  40.     public function addFile()  
  41.     {  
  42.         if(!empty($_FILES))  
  43.         {  
  44.             $this->_sMsg = '';  
  45.   
  46.             foreach($_FILES as $sKey => $aFiles)  
  47.             {  
  48.                 for($i = 0, $iNumFiles = count($aFiles['tmp_name']); $i < $iNumFiles$i++)  
  49.                 {  
  50.                     /** 
  51.                      * 获取上传文件的参数 
  52.                      */  
  53.                     $iErrCode   = $aFiles['error'][$i];  
  54.                     $iSize      = $aFiles['size'][$i];  
  55.                     $sFileName  = $aFiles['name'][$i];  
  56.                     $sTmpFile   = $aFiles['tmp_name'][$i];  
  57.                     $sFileDest  = $this->_sUploadDir . $sFileName;  
  58.                     $sTypeFile  = $aFiles['type'][$i];  
  59.   
  60.                     /** 
  61.                      * 检测文件类型 
  62.                      */  
  63.                     //$bIsImgExt = (strtolower(substr(strrchr($sFileName, '.'), 1))); // Get the file extension  
  64.                     //if(($bIsImgExt == 'jpeg' || $bIsImgExt == 'jpg' || $bIsImgExt == 'png' || $bIsImgExt == 'gif') && (strstr($sTypeFile, '/', true) === 'image'))  
  65.                     {  
  66.                         if($iErrCode == UPLOAD_ERR_OK)  
  67.                         {  
  68.                             move_uploaded_file($sTmpFile$sFileDest);  
  69.                               
  70.                             $this->_sMsg .= '<p style="color:green; font-weight:bold; text-align:center">Successful "' . $sFileName . '" file upload!</p>';  
  71.                             $this->_sMsg .= '<p style="text-align:center">Image type: ' . str_replace('image/'''$sTypeFile) . '<br />';  
  72.                             $this->_sMsg .= 'Size: ' . round($iSize / 1024) . ' KB<br />';  
  73.                             $this->_sMsg .= '<a href="' . $sFileDest . '" title="Click here to see the original file" target="_blank"><img src="' . $sFileDest . '" alt="' . $sFileName  . '" width="300" height="250" style="border:1.5px solid #ccc; border-radius:5px" /></a></p>';  
  74.                         }  
  75.                         else  
  76.                         {  
  77.                             $this->_sMsg .= '<p style="color:red; font-weight:bold; text-align:center">Error while downloading the file "' . $sFileName . '"<br />';  
  78.                             $this->_sMsg .= 'Error code: "' . $iErrCode . '"<br />';  
  79.                             $this->_sMsg .= 'Error message: "' . $this->_aErrFile[$iErrCode] . '"</p>';  
  80.                         }  
  81.                     }  
  82.                     //else  
  83.                     {  
  84.                     //    $this->_sMsg .= '<p style="color:red; font-weight:bold; text-align:center">File type incompatible. Please save the image in .jpg, .jpeg, .png or .gif</p>';  
  85.                     }  
  86.                 }  
  87.             }  
  88.         }  
  89.         else  
  90.         {  
  91.             $this->_sMsg = '<p style="color:red; font-weight:bold; text-align:center">You must select at least one file before submitting the form.</p>';  
  92.         }  
  93.   
  94.         return $this;  
  95.     }     
  96.   
  97.     /** 
  98.      * 中断文件上传 
  99.      * 
  100.      * @return object this 
  101.      */  
  102.     public function cancel()  
  103.     {  
  104.         if (!empty($_SESSION[$this->_sProgressKey]))  
  105.             $_SESSION[$this->_sProgressKey]['cancel_upload'] = true;  
  106.   
  107.         return $this;  
  108.     }  
  109.       
  110.      /** 
  111.      * @return 上传进度 
  112.      */  
  113.     public function progress()  
  114.     {  
  115.         if(!empty($_SESSION[$this->_sProgressKey]))  
  116.         {  
  117.             $aData = $_SESSION[$this->_sProgressKey];  
  118.             $iProcessed = $aData['bytes_processed'];  
  119.             $iLength    = $aData['content_length'];  
  120.             $iProgress  = ceil(100*$iProcessed / $iLength);  
  121.         }  
  122.         else  
  123.         {  
  124.             $iProgress = 100;  
  125.         }  
  126.   
  127.         return $iProgress;  
  128.     }  
  129.       
  130.      /** 
  131.      * @return object this 
  132.      */  
  133.      public function show()  
  134.      {  
  135.          ob_start();  
  136.          echo '<p><strong>$_FILES Result:</strong></p><pre>';  
  137.          var_dump($_FILES);  
  138.          echo '</pre>';  
  139.          echo '<p><strong>$_SESSION Result:</strong></p><pre>';  
  140.          var_dump($_SESSION);  
  141.          echo '</pre>';  
  142.          $this->_sMsg = ob_get_clean();  
  143.   
  144.          return $this;  
  145.      }  
  146.   
  147.     /** 
  148.      * Get the JSON informational message. 
  149.      * 
  150.      * @param integer $iStatus, 1 = success, 0 = error 
  151.      * @param string $sTxt 
  152.      * @return string JSON Format. 
  153.      */  
  154.      public static function jsonMsg($iStatus$sTxt)  
  155.      {  
  156.          return '{"status":' . $iStatus . ',"txt":"' . $sTxt . '"}';  
  157.      }  
  158.   
  159.     /** 
  160.      * Get the informational message. 
  161.      * 
  162.      * @return string 
  163.      */  
  164.     public function __toString()  
  165.     {  
  166.         return $this->_sMsg;  
  167.     }  
  168. }  

执行文件上传操作

[php]  view plain  copy
 print ? 在CODE上查看代码片 派生到我的代码片
  1. <?php  
  2. require_once ("upload.class.php");  
  3. $upload = new CUpload;  
  4. $upload->addFile();  
  5.   
  6. echo $upload;  
  7. /*$_SESSION["upload_progress_testUpload"] = array( 
  8.  "start_time" => 1234567890,   // 请求时间 
  9.  "content_length" => 57343257, // 上传文件总大小 
  10.  "bytes_processed" => 453489,  // 已经处理的大小 
  11.  "done" => false,              // 当所有上传处理完成后为TRUE 
  12.  "files" => array( 
  13.   0 => array( 
  14.    "field_name" => "file1",       // 表单中上传框的名字 
  15.    // The following 3 elements equals those in $_FILES 
  16.    "name" => "foo.avi", 
  17.    "tmp_name" => "/tmp/phpxxxxxx", 
  18.    "error" => 0, 
  19.    "done" => true,                // 当这个文件处理完成后会变成TRUE 
  20.    "start_time" => 1234567890,    // 这个文件开始处理时间 
  21.    "bytes_processed" => 57343250, // 这个文件已经处理的大小 
  22.   ), 
  23.   // An other file, not finished uploading, in the same request 
  24.   1 => array( 
  25.    "field_name" => "file2", 
  26.    "name" => "bar.avi", 
  27.    "tmp_name" => NULL, 
  28.    "error" => 0, 
  29.    "done" => false, 
  30.    "start_time" => 1234567899, 
  31.    "bytes_processed" => 54554, 
  32.   ), 
  33.  ) 
  34. );*/  
  35. ?>  
获取文件上传进度

[php]  view plain  copy
 print ? 在CODE上查看代码片 派生到我的代码片
  1. <?php  
  2. session_start();  
  3.   
  4. require_once ("upload.class.php");  
  5. echo (new CUpload())->progress();  
  6. ?>  


UI使用一些插件上传文件,就可以获取上传进度,不用这么麻烦


  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值