萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> PHP 程式設計

PHP 實作檔案上傳進度條:Session Upload Progress 完整教學

前言

大檔案上傳若無進度回饋,使用者易因等待焦慮而中斷操作。PHP 5.4+ 內建 session.upload_progress 機制,無需額外擴展即可實現即時進度顯示。本文從原理到完整前後端實作,打造流暢的上傳體驗。

核心原理

  1. 表單隱藏欄位 <input type="hidden" name="PHP_SESSION_UPLOAD_PROGRESS" value="upload_123">(名稱由 session.upload_progress.name 決定)。
  2. 上傳過程中,PHP 將進度資料寫入 $_SESSION['upload_progress_upload_123']。
  3. 前端透過 AJAX 輪詢獨立 PHP 腳本讀取 Session 進度資料。
  4. 上傳完成後,Session 資料自動清除(或手動清理)。

php.ini 關鍵設定

; 必須啟用
session.upload_progress.enabled = On
session.upload_progress.cleanup = On
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"
; 確保 session 可寫入、檔案上傳限制足夠
post_max_size = 100M
upload_max_filesize = 100M
max_execution_time = 300
max_input_time = 300

後端實作(兩支腳本)

upload.php - 處理上傳與進度查詢

<?php
session_start();
$progressKey = ini_get('session.upload_progress.prefix') . $_POST['progress_key'] ?? '';

if (isset($_GET['progress'])) {
    // 進度查詢端點
    header('Content-Type: application/json');
    if (isset($_SESSION[$progressKey])) {
        $data = $_SESSION[$progressKey];
        $progress = $data['content_length'] > 0
            ? round($data['bytes_processed'] / $data['content_length'] * 100, 2)
            : 0;
        echo json_encode(['progress' => $progress, 'bytes' => $data['bytes_processed'], 'total' => $data['content_length']]);
    } else {
        echo json_encode(['progress' => 0, 'bytes' => 0, 'total' => 0]);
    }
    exit;
}

// 檔案上傳處理
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_FILES['file'])) {
    $targetDir = __DIR__ . '/uploads/';
    $fileName = basename($_FILES['file']['name']);
    $targetPath = $targetDir . uniqid() . '_' . $fileName;

    if (move_uploaded_file($_FILES['file']['tmp_name'], $targetPath)) {
        echo json_encode(['success' => true, 'path' => $targetPath]);
    } else {
        http_response_code(500);
        echo json_encode(['success' => false, 'error' => '移動檔案失敗']);
    }
    exit;
}
?>

前端頁面(HTML + JavaScript)

<!DOCTYPE html>
<html><head><meta charset="utf-8"><title>上傳進度示範</title>
<style>
.progress-bar {width: 100%; height: 24px; background: #eee; border-radius: 4px; overflow: hidden;}
.progress-fill {height: 100%; background: #4caf50; width: 0%; transition: width 0.3s;}
</style></head><body>
<form id="uploadForm" enctype="multipart/form-data">
    <input type="hidden" name="PHP_SESSION_UPLOAD_PROGRESS" value="demo_upload">
    <input type="file" name="file" id="fileInput" required><br><br>
    <button type="submit">開始上傳</button>
</form>
<div class="progress-bar" style="margin-top:16px; display:none;" id="progressBar">
    <div class="progress-fill" id="progressFill"></div>
</div>
<div id="status"></div>

<script>
const form = document.getElementById('uploadForm');
const progressBar = document.getElementById('progressBar');
const progressFill = document.getElementById('progressFill');
const status = document.getElementById('status');
let pollTimer = null;

form.addEventListener('submit', async (e) => {
    e.preventDefault();
    const file = document.getElementById('fileInput').files[0];
    if (!file) return;

    progressBar.style.display = 'block';
    progressFill.style.width = '0%';
    status.textContent = '上傳中...';

    const formData = new FormData(form);
    // 開始上傳
    const uploadResp = fetch('upload.php', {method: 'POST', body: formData});

    // 輪詢進度
    pollTimer = setInterval(async () => {
        const res = await fetch('upload.php?progress=1&progress_key=demo_upload');
        const data = await res.json();
        progressFill.style.width = data.progress + '%';
        progressFill.textContent = data.progress.toFixed(1) + '%';
        if (data.progress >= 100) clearInterval(pollTimer);
    }, 500);

    try {
        const result = await uploadResp;
        const data = await result.json();
        if (data.success) {
            status.textContent = '上傳成功:' + data.path;
        } else {
            status.textContent = '失敗:' + data.error;
        }
    } catch (err) {
        status.textContent = '錯誤:' + err.message;
    } finally {
        clearInterval(pollTimer);
    }
});
</script>
</body></html>

進階優化技巧

  • 大檔案分片上傳:前端切片(如 5MB/片),後端合併,突破單次請求大小限制,支援斷點續傳。
  • WebSocket 替代輪詢:使用 Workerman/Swoole 推送進度,降低延遲與伺服器負載。
  • 多檔案佇列:串列上傳,顯示總體與單檔雙重進度。
  • 安全性:驗證 MIME、掃描病毒、隨機化儲存路徑、禁止直接存取上傳目錄。

常見坑點

  1. session.upload_progress.cleanup = On 會在請求結束自動刪除進度資料,輪詢腳本需在同一 Session 域下,且不能在上傳腳本結束前清理。
  2. 若使用 session_write_close() 釋放 Session 鎖,進度更新將停止,避免在上傳腳本中過早呼叫。
  3. Nginx client_max_body_size 預設 1MB,必須調大。

總結

Session Upload Progress 提供了零依賴的原生進度追蹤方案,配合簡單的 AJAX 輪詢即可實現專業級上傳體驗。對於超大檔案或高併發場景,建議升級至分片上傳 + WebSocket 架構。

copyright © 萬盛學電腦網 all rights reserved