萬盛學電腦網

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

PHP 大檔案上傳完整解決方案:分片上傳、斷點續傳、秒傳、WebUploader 整合

大檔上傳核心挑戰

  • PHP upload_max_filesize/post_max_size/memory_limit 限制。
  • Nginx client_max_body_size 限制。
  • 單次 HTTP 請求超時、網路中斷需重傳。
  • 並發大檔佔用大量記憶體/磁碟 I/O。

方案架構:分片 + 合併

前端 (WebUploader/Plupload)          後端 PHP API
    │                                      │
    ├─ 1. 計算檔案雜湊 (SparkMD5) ──────► │ (可選:秒傳檢查)
    │                                      │
    ├─ 2. 切片 (預設 5MB/片)              │
    │                                      │
    ├─ 3. 並行上傳分片 ─────────────────► /api/upload/chunk
    │   POST: chunkIndex, totalChunks,    │   → 儲存 /tmp/uploads/{fileHash}/part_{index}
    │   fileHash, filename                │
    │                                      │
    ├─ 4. 全部完成 ─────────────────────► /api/upload/merge
    │   POST: fileHash, filename, total   │   → 合併分片 → 移動到永久存儲 → 清理臨時
    │                                      │
    └─ 5. 返回最終 URL ◄─────────────────┘

後端核心 API 實作 (Slim/Laravel/原生均適用)

1. 分片上傳端點

<?php
// POST /api/upload/chunk
// 欄位: file (blob), chunkIndex (int), totalChunks (int), fileHash (string), filename (string)

$uploadDir = sys_get_temp_dir() . '/uploads';
$fileHash = $_POST['fileHash'] ?? '';
$chunkIndex = (int)($_POST['chunkIndex'] ?? 0);
$totalChunks = (int)($_POST['totalChunks'] ?? 1);
$filename = basename($_POST['filename'] ?? '');

if (!$fileHash || !$filename || !isset($_FILES['file'])) {
    http_response_code(400);
    exit(json_encode(['error'=>'參數缺失']));
}

$chunkDir = "$uploadDir/$fileHash";
if (!is_dir($chunkDir)) mkdir($chunkDir, 0755, true);

$chunkPath = "$chunkDir/part_$chunkIndex";
// 直接移動上傳的臨時檔 (高效)
if (!move_uploaded_file($_FILES['file']['tmp_name'], $chunkPath)) {
    http_response_code(500);
    exit(json_encode(['error'=>'分片儲存失敗']));
}

echo json_encode(['success'=>true, 'received'=>$chunkIndex+1, 'total'=>$totalChunks]);

2. 合併端點

<?php
// POST /api/upload/merge
// 欄位: fileHash, filename, totalChunks, mimeType (可選)

$fileHash = $_POST['fileHash'] ?? '';
$filename = basename($_POST['filename'] ?? '');
$totalChunks = (int)($_POST['totalChunks'] ?? 0);
$mimeType = $_POST['mimeType'] ?? 'application/octet-stream';

if (!$fileHash || !$filename || $totalChunks <= 0) {
    http_response_code(400);
    exit(json_encode(['error'=>'參數缺失']));
}

$chunkDir = sys_get_temp_dir() . "/uploads/$fileHash";
$finalDir = __DIR__ . '/storage/' . date('Y/m/d');
if (!is_dir($finalDir)) mkdir($finalDir, 0755, true);

// 生成唯一最終檔名
$ext = strtolower(pathinfo($filename, PATHINFO_EXTENSION));
$finalName = $fileHash . ($ext ? ".$ext" : '');
$finalPath = "$finalDir/$finalName";

// 串流合併 (低記憶體)
$outFp = fopen($finalPath, 'wb');
for ($i = 0; $i < $totalChunks; $i++) {
    $partPath = "$chunkDir/part_$i";
    if (!file_exists($partPath)) {
        fclose($outFp);
        @unlink($finalPath);
        http_response_code(400);
        exit(json_encode(['error'=>"缺少分片 $i"]));
    }
    $inFp = fopen($partPath, 'rb');
    stream_copy_to_stream($inFp, $outFp);
    fclose($inFp);
}
fclose($outFp);

// 清理分片目錄
array_map('unlink', glob("$chunkDir/*"));
rmdir($chunkDir);

// 記錄資料庫
// $pdo->prepare("INSERT INTO files (hash, name, path, mime, size) VALUES (?,?,?,?,?)")
//      ->execute([$fileHash, $filename, $finalPath, $mimeType, filesize($finalPath)]);

echo json_encode([
    'success' => true,
    'url' => '/storage/' . date('Y/m/d') . '/' . $finalName,
    'path' => $finalPath,
]);

3. 秒傳檢查端點 (可選)

<?php
// GET /api/upload/check?fileHash=xxx
$fileHash = $_GET['fileHash'] ?? '';
// 查資料庫
$stmt = $pdo->prepare("SELECT path FROM files WHERE hash = ?");
$stmt->execute([$fileHash]);
$row = $stmt->fetch();
if ($row) {
    echo json_encode(['exists'=>true, 'url'=>'/storage/...']);
} else {
    // 檢查臨時分片目錄是否有部分進度 (斷點續傳)
    $chunkDir = sys_get_temp_dir() . "/uploads/$fileHash";
    $uploaded = is_dir($chunkDir) ? count(glob("$chunkDir/part_*")) : 0;
    echo json_encode(['exists'=>false, 'uploadedChunks'=>$uploaded]);
}

前端整合:WebUploader 配置範例

<!-- HTML -->
<div id="uploader">
  <div class="queueList"><div id="dndArea" class="placeholder">拖拽檔案至此</div></div>
  <div class="statusBar" style="display:none"><div class="progress"><span class="text">0%</span></div></div>
</div>

<script src="webuploader.min.js"></script>
<script>
var uploader = WebUploader.create({
    pick: '#dndArea',
    dnd: '#dndArea',
    paste: document.body,
    accept: { title: 'Files', extensions: '*', mimeTypes: '*/*' },
    chunked: true,
    chunkSize: 5 * 1024 * 1024, // 5MB
    threads: 3, // 並行上傳 3 片
    fileVal: 'file',
    formData: {},
    prepareNextFile: true,
    auto: true,
    server: '/api/upload/chunk',
    // 計算雜湊 (WebUploader 內建 SparkMD5)
    checkChunkUploadedByResponse: function(chunk, response) {
        return response.success;
    }
});

// 秒傳檢查
uploader.on('fileQueued', function(file) {
    uploader.md5File(file).then(function(hash) {
        file.hash = hash;
        fetch('/api/upload/check?fileHash=' + hash)
            .then(r => r.json())
            .then(data => {
                if (data.exists) {
                    uploader.skipFile(file); // 直接標記完成
                    console.log('秒傳:', data.url);
                } else if (data.uploadedChunks > 0) {
                    console.log('斷點續傳,已上傳', data.uploadedChunks, '片');
                }
            });
    });
});

// 合併請求
uploader.on('uploadFinished', function() {
    // 實際上需監聽每個文件的 uploadComplete,收集所有文件再合併
    // 此處簡化:單文件上傳完畢即合併
});
uploader.on('uploadComplete', function(file) {
    fetch('/api/upload/merge', {
        method: 'POST',
        headers: {'Content-Type':'application/x-www-form-urlencoded'},
        body: new URLSearchParams({
            fileHash: file.hash,
            filename: file.name,
            totalChunks: file.chunks,
            mimeType: file.type
        })
    }).then(r => r.json()).then(console.log);
});
</script>

生產環境加固

  • 對象存儲直傳:前端獲取 STS 憑證 → 直傳 S3/OSS/COS,後端只負責簽名與合併通知,完全卸載應用服務器頻寬。
  • 分片並發控制:Nginx limit_req_zone 限制單 IP 上傳並發。
  • 惡意檔案檢測:合併後異步掃描 (ClamAV)、檢測 MIME 偽裝、圖片重壓縮 (去除 EXIF/惡意腳本)。
  • 分佈式部署:分片儲存於共享存儲 (NFS/GlusterFS/MinIO) 或各節點本地 + 合併時拉取;資料庫記錄分片分佈位置。
  • 進度持久化:Redis 記錄 upload:{hash}:received_chunks (Bitmap/Set),支援跨伺服器斷點續傳。
copyright © 萬盛學電腦網 all rights reserved