實現檔案上傳進度條基本是依靠JS外掛或HTML5的File API來完成,其實PHP配合ajax也能實現此功能。
PHP手冊對於session上傳進度是這麼介紹的:
當 session.upload_progress.enabled INI 選項開啟時,PHP 能夠在每一個檔案上傳時監測上傳進度。 這個資訊對上傳請求自身並沒有什麼幫助,但在檔案上傳時應用可以傳送一個POST請求到終端(例如通過XHR)來檢查這個狀態 當一個上傳在處理中,同時POST一個與INI中設定的session.upload_progress.name同名變數時,上傳進度可以在$_SESSION中獲得。 當PHP檢測到這種POST請求時,它會在$_SESSION中新增一組資料, 索引是 session.upload_progress.prefix 與 session.upload_progress.name連線在一起的值。 通常這些鍵值可以通過讀取INI設定來獲得,例如 <?php
$key = ini_get("session.upload_progress.prefix") . ini_get("session.upload-progress.name");
var_dump($_SESSION[$key]);
?> 通過將$_SESSION[$key]["cancel_upload"]設定為TRUE,還可以取消一個正在處理中的檔案上傳。 當在同一個請求中上傳多個檔案,它僅會取消當前正在處理的檔案上傳和未處理的檔案上傳,但是不會移除那些已經完成的上傳。 當一個上傳請求被這麼取消時,$_FILES中的error將會被設定為 UPLOAD_ERR_EXTENSION。 session.upload_progress.freq 和 session.upload_progress.min_freq INI選項控制了上傳進度資訊應該多久被重新計算一次。 通過合理設定這兩個選項的值,這個功能的開銷幾乎可以忽略不計。 注意:為了使這個正常工作,web伺服器的請求緩衝區需要禁用,否則 PHP可能僅當檔案完全上傳完成時才能收到檔案上傳請求。 已知會緩衝這種大請求的程式有Nginx。
下面原理介紹:
當瀏覽器向伺服器端上傳一個檔案時,PHP將會把此次檔案上傳的詳細資訊(如上傳時間、上傳進度等)儲存在session當中。然後,隨著上傳的進行,週期性的更新session中的資訊。這樣,瀏覽器端就可以使用Ajax週期性的請求一個伺服器端指令碼,由該指令碼返回session中的進度資訊;瀏覽器端的Javascript即可根據這些資訊顯示/更新進度條了。
php.ini需配置以下選項
session.upload_progress.enabled = "1"
session.upload_progress.cleanup = "1"
session.upload_progress.prefix = "upload_progress_"
session.upload_progress.name = "PHP_SESSION_UPLOAD_PROGRESS"
session.upload_progress.freq = "1%"
session.upload_progress.min_freq = "1"
其中enabled控制upload_progress功能的開啟與否,預設開啟;
cleanup 則設定當檔案上傳的請求提交完成後,是否清除session的相關資訊,預設開啟,如果需要除錯$_SESSION,則應該設為Off。
prefix 和 name 兩項用來設定進度資訊在session中儲存的變數名/鍵名。
freq 和 min_freq 兩項用來設定伺服器端對進度資訊的更新頻率。合理的設定這兩項可以減輕伺服器的負擔。
在上傳檔案的表單中,需要為該次上傳設定一個識別符號,並在接下來的過程中使用該識別符號來引用進度資訊。
具體的,在上傳表單中需要有一個隱藏的input,它的name屬性為php.ini中 session.upload_progress.name 的值;它的值為一個由你自己定義的識別符號。如下:
程式碼如下:
<input type="hidden" name="<?php echo ini_get('session.upload_progress.name'); ?>" value="test" />
接到檔案上傳的表單後,PHP會在$_SESSION變數中新建鍵,鍵名是一個將session.upload_progress.prefix的值與上面自定義的識別符號連線後得到的字串,可以這樣得到:
程式碼如下:
$name = ini_get('session.upload_progress.name');
$key = ini_get('session.upload_progress.prefix') . $_POST[$name];
$_SESSION[$key]; // 這裡就是此次檔案上傳的進度資訊了
$_SESSION[$key]這個變數的結構是這樣的:
array (
'upload_progress_test' => array (
'start_time' => 1491494993, // 開始時間
'content_length' => 1410397, // POST請求的總資料長度
'bytes_processed' => 1410397, // 已收到的資料長度
'done' => true, // 請求是否完成 true表示完成,false未完成
'files' => array (
0 => array (
'field_name' => 'file1',
'name' => 'test.jpg',
'tmp_name' => 'D:\\wamp\\tmp\\phpE181.tmp',
'error' => 0,
'done' => true,
'start_time' => 1491494993,
'bytes_processed' => 1410096,
),
),
),
);
這樣,我們就可以使用其中的 content_length 和 bytes_processed 兩項來得到進度百分比。
原理介紹完了,下面我們來完整的實現一個基於PHP和Javascript的檔案上傳進度條。
上傳表單index.php
<?php session_start(); ?>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="utf-8">
<title>PHP(5.4) Session 上傳進度 Demo</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="keywords" content=""/>
<meta name="description" content=""/>
<meta name="author" content="">
<link href="https://cdn.bootcss.com/bootstrap/4.0.0-alpha.2/css/bootstrap.min.css" rel="stylesheet"> <style type="text/css">
body{
font-size:1em;
color:#333;
font-family: "宋體", Arial, sans-serif;
}
h1, h2, h3, h4, h5, h6{
font-family: "宋體", Georgia, serif;
color:#000;
line-height:1.8em;
margin:0;
}
h1{ font-size:1.8em; }
#wrap{
margin-top:15px;
margin-bottom:50px;
background:#fff;
border-radius:5px;
box-shadow:inset 0 0 3px #000,
0 0 3px #eee;
}
#header{
border-radius:5px 5px 0 0;
box-shadow:inset 0 0 3px #000;
padding:0 15px;
color:#fff;
background: #333333;
}
#header h1{
color:#fff;
} #article{
padding:0 15px;
}
#footer{
text-align:center;
border-top:1px solid #ccc;
border-radius:0 0 5px 5px;
} .progress {
width: 100%;
border: 1px solid #4da8fe;
border-radius: 40px;
height: 20px;
position: relative;
} .progress .labels {
position: relative;
text-align: center; } .progress .bar {
position: absolute;
left: 0;
top: 0;
background: #4D90FE;
height: 20px;
line-height:20px;
border-radius: 40px;
min-width: 20px;
} .report-file {
display: block;
position: relative;
width: 120px;
height: 28px;
overflow: hidden;
border: 1px solid #428bca;
background: none repeat scroll 0 0 #428bca;
color: #fff;
cursor: pointer;
text-align: center;
float: left;
margin-right:5px;
}
.report-file span {
cursor: pointer;
display: block;
line-height: 28px;
}
.file-prew {
cursor: pointer;
position: absolute;
top: 0;
left:0;
width: 120px;
height: 30px;
font-size: 100px;
opacity: 0;
filter: alpha(opacity=0);
} .container{
padding-left:0;
padding-right:0;
margin:0 auto;
}
</style> </head>
<body> <div id="wrap" class="container"> <div id="header">
<h1>Session上傳進度 Demo</h1>
</div>
<div id="article"> <form id="upload-form" action="upload.php" method="POST" enctype="multipart/form-data" style="margin:15px 0"
target="hidden_iframe">
<input type="hidden" name="<?php echo ini_get("session.upload_progress.name"); ?>" value="test"/>
<div class="report-file">
<span>上傳檔案…</span><input tabindex="3" size="3" name="file1" class="file-prew" type="file" onchange="document.getElementById('textName').value=this.value">
</div>
<input type="text" id="textName" style="height: 28px;border:1px solid #f1f1f1" />
<p>
<input type="submit" class="btn btn-default" value="上傳"/>
</p>
</form> <div id="progress" class="progress" style="margin-bottom:15px;display:none;">
<div class="bar" style="width:0%;"></div>
<div class="labels">0%</div>
</div> </div> <!-- #article --> <div id="footer">
<p> </p>
</div>
</div><!-- #wrap --> <iframe id="hidden_iframe" name="hidden_iframe" src="about:blank" style="display:none;"></iframe> <script src="https://cdn.bootcss.com/jquery/3.1.1/jquery.min.js"></script>
<script type="text/javascript">
function fetch_progress() {
$.get('progress.php', {'<?php echo ini_get("session.upload_progress.name"); ?>': 'test'}, function (data) {
var progress = parseInt(data); $('#progress .labels').html(progress + '%');
$('#progress .bar').css('width', progress + '%'); if (progress < 100) {
setTimeout('fetch_progress()', 500);
} else {
$('#progress .labels').html('100%');
}
}, 'html');
} $('#upload-form').submit(function () {
$('#progress').show(); //圖片比較小,看不出進度條載入效果,初始設33%
$('#progress .labels').html('33%');
$('#progress .bar').css('width', '33%'); setTimeout('fetch_progress()', 500);
});
</script>
</body>
</html>
注意表單中的session.upload_progress.name隱藏項,值設定為了test。表單中僅有一個檔案上傳input,如果需要,你可以新增多個。
這裡需要特別注意一下表單的target屬性,這裡設定指向了一個當前頁面中的iframe。這一點很關鍵,通過設定target屬性,讓表單提交後的頁面顯示在iframe中,從而避免當前的頁面跳轉。因為我們還得在當前頁面顯示進度條呢。
上傳檔案upload.php
<?php
/**
* 上傳檔案
*/
if(is_uploaded_file($_FILES['file1']['tmp_name'])){
//unlink($_FILES['file1']['tmp_name']);
$fileName = 'pic_' . date('YmdHis') . mt_rand(10000,99999);
$ext = substr($_FILES['file1']['name'], strrpos($_FILES['file1']['name'], '.')); move_uploaded_file($_FILES['file1']['tmp_name'], $fileName . $ext);
}
ajax獲取上傳進度progress.php
<?php
/**
* AJAX獲取上傳檔案進度
*/
session_start(); $i = ini_get('session.upload_progress.name');
//session.upload_progress.name = "PHP_SESSION_UPLOAD_PROGRESS" $key = ini_get("session.upload_progress.prefix") . $_GET[$i];
//session.upload_progress.prefix = "upload_progress_" . 'test' if (!empty($_SESSION[$key])) {
$current = $_SESSION[$key]["bytes_processed"]; // 已收到的資料長度
$total = $_SESSION[$key]["content_length"]; // POST請求的總資料長度
echo $current < $total ? ceil($current / $total * 100) : 100;
}else{
echo 100;
}
注意事項:
1.input標籤的位置name為session.upload_progress.name的input標籤一定要放在檔案input <input type="file" /> 的前面。
2.通過設定 $_SESSION[$key]['cancel_upload'] = true 可取消當次上傳。但僅能取消正在上傳的檔案和尚未開始的檔案。已經上傳成功的檔案不會被刪除。
3.應該通過 setTimeout() 來呼叫 fetch_progress(),這樣可以確保一次請求返回之後才開始下一次請求。如果使用 setInterval() 則不能保證這一點,有可能導致進度條出現'不進反退'。