萬盛學電腦網

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

使用百度雲 BCS PHP SDK 實作批量下載雲盤檔案

前言

百度開放雲(BCS)提供物件儲存服務,配合官方 PHP SDK 可輕鬆實作批量下載、同步備份、離線處理等自動化流程。本文示範完整的批量下載實作,含分頁列舉、目錄遞迴建立、錯誤重試與進度追蹤。

環境準備

  1. 下載 SDK:官方 SDK 頁面
  2. 需檔案:bcs.class.php、krumo/class.krumo.php(除錯用)
  3. 取得 Access Key (AK) 與 Secret Key (SK)
  4. 確認 Bucket 名稱與權限(需讀取權限)

完整批量下載實作

<?php
/**
 * 百度 BCS 批量下載器
 * 支援:分頁列舉、目錄結構保留、斷點續傳、錯誤重試、進度日誌
 */
class BcsBatchDownloader
{
    private $bcs;
    private $bucket;
    private $localBase;
    private $limit = 1000;      // 每次列舉數量
    private $maxRetries = 3;    // 下載重試次數
    private $stats = ['total' => 0, 'success' => 0, 'failed' => 0, 'skipped' => 0];

    public function __construct(string $ak, string $sk, string $bucket, string $host = 'bcs.duapp.com', string $localBase = '.')
    {
        require_once __DIR__ . '/bcs.class.php';
        $this->bcs = new BaiduBCS($ak, $sk, $host);
        $this->bucket = $bucket;
        $this->localBase = rtrim($localBase, '/');
    }

    public function downloadAll(): array
    {
        ini_set('max_execution_time', 0); // 移除執行時間限制
        $start = 0;

        do {
            $response = $this->listObjects($start);
            if (!$response || empty($response->object_list)) {
                break;
            }

            foreach ($response->object_list as $object) {
                $this->stats['total']++;
                if ($object->is_dir) {
                    $this->ensureDir($object->object);
                    $this->stats['skipped']++;
                    continue;
                }

                $success = $this->downloadObject($object);
                $success ? $this->stats['success']++ : $this->stats['failed']++;
            }

            $start += $this->limit;
            // 禮讓 API,避免觸發頻率限制
            usleep(200000); // 0.2 秒

        } while (true);

        return $this->stats;
    }

    private function listObjects(int $start): ?object
    {
        for ($attempt = 1; $attempt <= $this->maxRetries; $attempt++) {
            try {
                $resp = $this->bcs->list_object($this->bucket, [
                    'start' => $start,
                    'limit' => $this->limit,
                ]);
                if ($resp->isOK()) {
                    return json_decode($resp->body);
                }
                error_log("List objects failed: {$resp->status} {$resp->body}");
            } catch (\Throwable $e) {
                error_log("List objects exception: " . $e->getMessage());
            }
            if ($attempt < $this->maxRetries) sleep(2 ** $attempt); // 指數退避
        }
        return null;
    }

    private function downloadObject(object $object): bool
    {
        $remotePath = $object->object; // 含前導斜線,如 /folder/file.txt
        $localPath = $this->localBase . $remotePath;
        $dir = dirname($localPath);

        $this->ensureDir($dir);

        for ($attempt = 1; $attempt <= $this->maxRetries; $attempt++) {
            try {
                $resp = $this->bcs->get_object($this->bucket, $remotePath, [
                    'fileWriteTo' => $localPath,
                ]);
                if ($resp->isOK()) {
                    // 驗證檔案大小
                    if (isset($object->size) && filesize($localPath) != $object->size) {
                        error_log("Size mismatch: $remotePath (expected {$object->size}, got " . filesize($localPath) . ")");
                        unlink($localPath);
                        continue;
                    }
                    error_log("Downloaded: $remotePath");
                    return true;
                }
                error_log("Download failed: $remotePath - {$resp->status} {$resp->body}");
            } catch (\Throwable $e) {
                error_log("Download exception: $remotePath - " . $e->getMessage());
            }
            if ($attempt < $this->maxRetries) sleep(2 ** $attempt);
        }
        return false;
    }

    private function ensureDir(string $dir): void
    {
        if (!is_dir($dir)) {
            mkdir($dir, 0755, true);
        }
    }

    public function getStats(): array
    {
        return $this->stats;
    }
}

// 使用範例
$downloader = new BcsBatchDownloader(
    '你的_AK',
    '你的_SK',
    '目標_bucket名稱',
    'bcs.duapp.com',
    '/data/backup/bcs' // 本地儲存根目錄
);

echo "開始批量下載...\n";
$stats = $downloader->downloadAll();
echo "完成統計:\n";
print_r($stats);
/*
Array
(
    [total] => 1250
    [success] => 1245
    [failed] => 3
    [skipped] => 2
)
*/

關鍵實作細節解析

1. 分頁列舉策略

BCS list_object 支援 start(起始索引)與 limit(單次上限,官方建議 ≤1000)。迴圈累加 start 直到無資料返回。

2. 目錄結構還原

物件路徑 /photos/2024/01/photo.jpg 對應本地 $localBase/photos/2024/01/photo.jpg。ensureDir() 遞迴建立父目錄。

3. 斷點續傳設計

  • 記錄已下載物件的 etag 或 lastModified 至本地索引檔(SQLite/JSON)
  • 重啟時比對,跳過未變更檔案
  • 本範例為簡化未實作,生產環境強烈建議加入

4. 錯誤重試與指數退避

網路抖動、API 限流屬常態。maxRetries=3 + sleep(2^attempt) 能有效吸收暫時性故障。

5. 大檔案記憶體保護

使用 'fileWriteTo' => $localPath 直接串流寫入磁碟,避免 file_get_contents 將大檔案載入記憶體導致 OOM。

進階擴充建議

  • 並行下載: 使用 curl_multi 或 pthreads(CLI 環境)同時下載多檔案
  • 增量同步: 記錄上次同步時間,配合 list_object 的 marker 或時間篩選
  • 監控告警: 失敗率超過閾值發送通知(Slack/Email/企業微信)
  • 校驗和驗證: 下載後計算 MD5/SHA256 與 BCS 回傳的 Content-MD5 比對
  • CLI 專用: 批量作業建議在 CLI 模式執行,避免 Web 超時限制

常見問題排查

現象可能原因解決方向
列舉回傳 403AK/SK 權限不足、Bucket 不存在、Referer 限制檢查金鑰權限、Bucket 名稱、控制台 Referer 白名單
下載大檔案中斷PHP memory_limit、max_execution_time、nginx proxy_read_timeoutCLI 執行、調整限制、使用 fileWriteTo 串流
中文檔名亂碼URL 編碼/解碼不一致統一使用 rawurlencode/rawurldecode,檢查 SDK 內部處理
速度極慢單執行緒、網路延遲、API 限流並行下載、CDN 加速、避開尖峰時段

總結

百度 BCS PHP SDK 提供完整的物件儲存操作介面。批量下載的關鍵在於分頁列舉、串流寫入、目錄還原、重試機制、進度可觀測。本文提供的 BcsBatchDownloader 類別可作為生產環境備份、遷移、同步任務的起點,根據業務規模擴充並行、增量、校驗等功能,即可構建穩健的資料搬運管線。

copyright © 萬盛學電腦網 all rights reserved