業務場景:用戶在B站點上傳文件,實際存儲至A站點(不同域名/服務器)。本文提供三種成熟方案對比,推薦「B站點代理上傳至A站點API」架構,並給出完整接口設計、簽名驗證、錯誤處理代碼。
| 方案 | 原理 | 優點 | 缺點 | 適用場景 |
|---|---|---|---|---|
| 1. 前端直傳A站點(CORS) | 瀏覽器直接POST到A站點API,A配置CORS允許B域名 | 減輕B服務器帶寬、延遲最低 | 暴露A存儲接口、CORS配置複雜、難以在B側做業務校驗 | 公共存儲服務、簡單業務 |
| 2. B站點代理上傳(推薦) | 用戶上傳到B,B驗證後用cURL轉發到A API | B完全控制業務邏輯、權限、審計;A只需提供內部API | B消耗雙倍帶寬、延遲增加 | 強業務關聯、需合規審計、跨內網環境 |
| 3. 預簽名URL/臨時憑證 | A生成帶簽名的上傳URL/Token,B前端獲取後直傳 | 帶寬優化、A可控過期時間權限 | 實現復雜、需雙方協議統一 | 大文件、高併發、對象存儲(S3/OSS) |
<?php // A站點 api/upload.php
// 僅允許內網IP或簽名驗證
$allowedIps = ['10.0.0.0/8', '192.168.0.0/16'];
$clientIp = $_SERVER['REMOTE_ADDR'];
if (!ip_in_ranges($clientIp, $allowedIps) && !verify_signature($_POST, $_FILES)) {
http_response_code(403); exit('Forbidden');
}
// 處理上傳(同單機上傳邏輯)
$file = $_FILES['file'];
// ... 驗證、移動、入庫 ...
echo json_encode(['code' => 0, 'data' => ['file_id' => $id, 'url' => $url]]);
<?php // B站點 UploadController.php
public function upload(Request $request) {
// 1. B側業務校驗:權限、文件類型、大小、防刷
$this->validate($request, [
'file' => 'required|file|max:10240|mimes:jpg,jpeg,png,pdf,doc,docx',
]);
$file = $request->file('file');
// 2. 構建轉發請求
$apiUrl = config('services.storage_a.upload_url'); // https://internal-a/api/upload
$apiKey = config('services.storage_a.api_key');
$timestamp = time();
$nonce = bin2hex(random_bytes(8));
$signData = $apiKey . $timestamp . $nonce . $file->getSize() . $file->getClientOriginalName();
$signature = hash_hmac('sha256', $signData, $apiKey);
// 3. cURL multipart轉發
$ch = curl_init($apiUrl);
$cfile = new CURLFile($file->getRealPath(), $file->getMimeType(), $file->getClientOriginalName());
$postFields = [
'file' => $cfile,
'timestamp' => $timestamp,
'nonce' => $nonce,
'signature' => $signature,
'business_id' => $request->user()->id, // 透傳業務標識
];
curl_setopt_array($ch, [
CURLOPT_POST => true,
CURLOPT_POSTFIELDS => $postFields,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_TIMEOUT => 30,
CURLOPT_SSL_VERIFYPEER => false, // 內網可關閉,或配置CA
]);
$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
// 4. 處理響應
if ($httpCode !== 200) {
Log::error('存儲服務異常', ['code' => $httpCode, 'body' => $response]);
return response()->json(['msg' => '存儲服務暫時不可用'], 503);
}
$result = json_decode($response, true);
if ($result['code'] !== 0) {
return response()->json(['msg' => $result['msg']], 400);
}
// 5. B側記錄文件元數據(可選)
FileRecord::create([
'user_id' => $request->user()->id,
'storage_file_id' => $result['data']['file_id'],
'url' => $result['data']['url'],
'original_name' => $file->getClientOriginalName(),
]);
return response()->json(['url' => $result['data']['url']]);
}
api_key,簽名包含時間戳、隨機數、文件元信息。finfo檢查,防繞過B側驗證。代理上傳模式清晰劃分職責,是企業級跨系統文件上傳的標準架構。