百度開放雲(BCS)提供物件儲存服務,配合官方 PHP SDK 可輕鬆實作批量下載、同步備份、離線處理等自動化流程。本文示範完整的批量下載實作,含分頁列舉、目錄遞迴建立、錯誤重試與進度追蹤。
bcs.class.php、krumo/class.krumo.php(除錯用)<?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
)
*/
BCS list_object 支援 start(起始索引)與 limit(單次上限,官方建議 ≤1000)。迴圈累加 start 直到無資料返回。
物件路徑 /photos/2024/01/photo.jpg 對應本地 $localBase/photos/2024/01/photo.jpg。ensureDir() 遞迴建立父目錄。
etag 或 lastModified 至本地索引檔(SQLite/JSON)網路抖動、API 限流屬常態。maxRetries=3 + sleep(2^attempt) 能有效吸收暫時性故障。
使用 'fileWriteTo' => $localPath 直接串流寫入磁碟,避免 file_get_contents 將大檔案載入記憶體導致 OOM。
curl_multi 或 pthreads(CLI 環境)同時下載多檔案list_object 的 marker 或時間篩選Content-MD5 比對| 現象 | 可能原因 | 解決方向 |
|---|---|---|
| 列舉回傳 403 | AK/SK 權限不足、Bucket 不存在、Referer 限制 | 檢查金鑰權限、Bucket 名稱、控制台 Referer 白名單 |
| 下載大檔案中斷 | PHP memory_limit、max_execution_time、nginx proxy_read_timeout | CLI 執行、調整限制、使用 fileWriteTo 串流 |
| 中文檔名亂碼 | URL 編碼/解碼不一致 | 統一使用 rawurlencode/rawurldecode,檢查 SDK 內部處理 |
| 速度極慢 | 單執行緒、網路延遲、API 限流 | 並行下載、CDN 加速、避開尖峰時段 |
百度 BCS PHP SDK 提供完整的物件儲存操作介面。批量下載的關鍵在於分頁列舉、串流寫入、目錄還原、重試機制、進度可觀測。本文提供的 BcsBatchDownloader 類別可作為生產環境備份、遷移、同步任務的起點,根據業務規模擴充並行、增量、校驗等功能,即可構建穩健的資料搬運管線。