php如何實(shí)現(xiàn)上傳進(jìn)度條

php實(shí)現(xiàn)上傳進(jìn)度條的方法:首先向服務(wù)器端上傳一個(gè)文件;然后用PHP將此次文件上傳的詳細(xì)信息存儲在session當(dāng)中;接著用Ajax周期性的請求一個(gè)服務(wù)器端腳本;最后通過瀏覽器端的Javascript顯示更新進(jìn)度條即可。

創(chuàng)新互聯(lián)專注為客戶提供全方位的互聯(lián)網(wǎng)綜合服務(wù),包含不限于做網(wǎng)站、成都網(wǎng)站設(shè)計(jì)、芒康網(wǎng)絡(luò)推廣、微信小程序、芒康網(wǎng)絡(luò)營銷、芒康企業(yè)策劃、芒康品牌公關(guān)、搜索引擎seo、人物專訪、企業(yè)宣傳片、企業(yè)代運(yùn)營等,從售前售中售后,我們都將竭誠為您服務(wù),您的肯定,是我們大的嘉獎;創(chuàng)新互聯(lián)為所有大學(xué)生創(chuàng)業(yè)者提供芒康建站搭建服務(wù),24小時(shí)服務(wù)熱線:13518219792,官方網(wǎng)址:muchs.cn

推薦:《PHP視頻教程》

實(shí)現(xiàn)文件上傳進(jìn)度條基本是依靠JS插件或HTML5的File API來完成,其實(shí)PHP配合ajax也能實(shí)現(xiàn)此功能。

PHP手冊對于session上傳進(jìn)度是這么介紹的:

當(dāng) session.upload_progress.enabled INI 選項(xiàng)開啟時(shí),PHP 能夠在每一個(gè)文件上傳時(shí)監(jiān)測上傳進(jìn)度。 這個(gè)信息對上傳請求自身并沒有什么幫助,但在文件上傳時(shí)應(yīng)用可以發(fā)送一個(gè)POST請求到終端(例如通過XHR)來檢查這個(gè)狀態(tài) 

當(dāng)一個(gè)上傳在處理中,同時(shí)POST一個(gè)與INI中設(shè)置的session.upload_progress.name同名變量時(shí),上傳進(jìn)度可以在$_SESSION中獲得。 當(dāng)PHP檢測到這種POST請求時(shí),它會在$_SESSION中添加一組數(shù)據(jù), 索引是 session.upload_progress.prefix 與 session.upload_progress.name連接在一起的值。 通常這些鍵值可以通過讀取INI設(shè)置來獲得,例如 

<?php
$key = ini_get("session.upload_progress.prefix") . ini_get("session.upload-progress.name");
var_dump($_SESSION[$key]);
?>  

通過將$_SESSION[$key]["cancel_upload"]設(shè)置為TRUE,還可以取消一個(gè)正在處理中的文件上傳。 當(dāng)在同一個(gè)請求中上傳多個(gè)文件,它僅會取消當(dāng)前正在處理的文件上傳和未處理的文件上傳,但是不會移除那些已經(jīng)完成的上傳。 當(dāng)一個(gè)上傳請求被這么取消時(shí),$_FILES中的error將會被設(shè)置為 UPLOAD_ERR_EXTENSION。 

session.upload_progress.freq 和 session.upload_progress.min_freq INI選項(xiàng)控制了上傳進(jìn)度信息應(yīng)該多久被重新計(jì)算一次。 通過合理設(shè)置這兩個(gè)選項(xiàng)的值,這個(gè)功能的開銷幾乎可以忽略不計(jì)。 

注意:為了使這個(gè)正常工作,web服務(wù)器的請求緩沖區(qū)需要禁用,否則 PHP可能僅當(dāng)文件完全上傳完成時(shí)才能收到文件上傳請求。 已知會緩沖這種大請求的程序有Nginx。

下面原理介紹:
當(dāng)瀏覽器向服務(wù)器端上傳一個(gè)文件時(shí),PHP將會把此次文件上傳的詳細(xì)信息(如上傳時(shí)間、上傳進(jìn)度等)存儲在session當(dāng)中。然后,隨著上傳的進(jìn)行,周期性的更新session中的信息。這樣,瀏覽器端就可以使用Ajax周期性的請求一個(gè)服務(wù)器端腳本,由該腳本返回session中的進(jìn)度信息;瀏覽器端的Javascript即可根據(jù)這些信息顯示/更新進(jìn)度條了。

php.ini需配置以下選項(xiàng)

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功能的開啟與否,默認(rèn)開啟;
cleanup 則設(shè)置當(dāng)文件上傳的請求提交完成后,是否清除session的相關(guān)信息,默認(rèn)開啟,如果需要調(diào)試$_SESSION,則應(yīng)該設(shè)為Off。
prefix 和 name 兩項(xiàng)用來設(shè)置進(jìn)度信息在session中存儲的變量名/鍵名。
freq 和 min_freq 兩項(xiàng)用來設(shè)置服務(wù)器端對進(jìn)度信息的更新頻率。合理的設(shè)置這兩項(xiàng)可以減輕服務(wù)器的負(fù)擔(dān)。
在上傳文件的表單中,需要為該次上傳設(shè)置一個(gè)標(biāo)識符,并在接下來的過程中使用該標(biāo)識符來引用進(jìn)度信息。

具體的,在上傳表單中需要有一個(gè)隱藏的input,它的name屬性為php.ini中 session.upload_progress.name 的值;它的值為一個(gè)由你自己定義的標(biāo)識符。如下:
代碼如下:

<input type="hidden" name="<?php echo ini_get('session.upload_progress.name'); ?>" value="test" />

接到文件上傳的表單后,PHP會在$_SESSION變量中新建鍵,鍵名是一個(gè)將session.upload_progress.prefix的值與上面自定義的標(biāo)識符連接后得到的字符串,可以這樣得到:
代碼如下:

$name = ini_get('session.upload_progress.name');
$key = ini_get('session.upload_progress.prefix') . $_POST[$name];
$_SESSION[$key]; // 這里就是此次文件上傳的進(jìn)度信息了

$_SESSION[$key]這個(gè)變量的結(jié)構(gòu)是這樣的:

array (
	'upload_progress_test' => array (
		'start_time' => 1491494993,   // 開始時(shí)間
		'content_length' => 1410397,  // POST請求的總數(shù)據(jù)長度
		'bytes_processed' => 1410397, // 已收到的數(shù)據(jù)長度
		'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 兩項(xiàng)來得到進(jìn)度百分比。

原理介紹完了,下面我們來完整的實(shí)現(xiàn)一個(gè)基于PHP和Javascript的文件上傳進(jìn)度條。

上傳表單index.php

<?php session_start(); ?>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="utf-8">
    <title>PHP(5.4) Session 上傳進(jìn)度 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>

<p id="wrap" class="container">

    <p id="header">
        <h1>Session上傳進(jìn)度 Demo</h1>
    </p>
    <p 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"/>
            <p class="report-file">
                <span>上傳文件…</span><input tabindex="3" size="3" name="file1" class="file-prew" type="file" onchange="document.getElementById('textName').value=this.value">
            </p>
            <input type="text" id="textName" style="height: 28px;border:1px solid #f1f1f1" />
            <p>
                <input type="submit" class="btn btn-default" value="上傳"/>
            </p>
        </form>

        <p id="progress" class="progress" style="margin-bottom:15px;display:none;">
            <p class="bar" style="width:0%;"></p>
            <p class="labels">0%</p>
        </p>

    </p> <!-- #article -->

    <p id="footer">
        <p> </p>
    </p>
</p><!-- #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();

        //圖片比較小,看不出進(jìn)度條加載效果,初始設(shè)33%
        $('#progress .labels').html('33%');
        $('#progress .bar').css('width', '33%');

        setTimeout('fetch_progress()', 500);
    });
</script>
</body>
</html>

注意表單中的session.upload_progress.name隱藏項(xiàng),值設(shè)置為了test。表單中僅有一個(gè)文件上傳input,如果需要,你可以添加多個(gè)。
這里需要特別注意一下表單的target屬性,這里設(shè)置指向了一個(gè)當(dāng)前頁面中的iframe。這一點(diǎn)很關(guān)鍵,通過設(shè)置target屬性,讓表單提交后的頁面顯示在iframe中,從而避免當(dāng)前的頁面跳轉(zhuǎn)。因?yàn)槲覀冞€得在當(dāng)前頁面顯示進(jìn)度條呢。

上傳文件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獲取上傳進(jìn)度progress.php

<?php
/**
 * AJAX獲取上傳文件進(jìn)度
 */
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"]; // 已收到的數(shù)據(jù)長度
	$total   = $_SESSION[$key]["content_length"];  // POST請求的總數(shù)據(jù)長度
	echo $current < $total ? ceil($current / $total * 100) : 100;
}else{
	echo 100;
}

注意事項(xiàng):
1.input標(biāo)簽的位置name為session.upload_progress.name的input標(biāo)簽一定要放在文件input <input type="file" /> 的前面。
2.通過設(shè)置 $_SESSION[$key]['cancel_upload'] = true 可取消當(dāng)次上傳。但僅能取消正在上傳的文件和尚未開始的文件。已經(jīng)上傳成功的文件不會被刪除。
3.應(yīng)該通過 setTimeout() 來調(diào)用 fetch_progress(),這樣可以確保一次請求返回之后才開始下一次請求。如果使用 setInterval() 則不能保證這一點(diǎn),有可能導(dǎo)致進(jìn)度條出現(xiàn)'不進(jìn)反退'。

網(wǎng)頁題目:php如何實(shí)現(xiàn)上傳進(jìn)度條
網(wǎng)站網(wǎng)址:http://muchs.cn/article6/chsiig.html

成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供靜態(tài)網(wǎng)站網(wǎng)站維護(hù)、網(wǎng)站建設(shè)Google、響應(yīng)式網(wǎng)站建站公司

廣告

聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來源: 創(chuàng)新互聯(lián)

綿陽服務(wù)器托管