前端通過 `fetch`/`XMLHttpRequest` 直接發送二進制圖片體(非 `multipart/form-data`),PHP 需從 `php://input` 讀取原始流並寫入檔案。本文給出完整接收、驗證、保存、錯誤處理流程。
<?php
// 1. 讀取原始輸入流(僅能讀取一次)
$raw = file_get_contents('php://input');
if ($raw === false || $raw === '') {
http_response_code(400);
exit('Empty request body');
}
// 2. 可選:驗證 Content-Type
$contentType = $_SERVER['CONTENT_TYPE'] ?? '';
if (!str_starts_with($contentType, 'image/')) {
http_response_code(415);
exit('Unsupported Media Type');
}
// 3. 生成安全檔名
$ext = match (true) {
str_contains($contentType, 'jpeg') => 'jpg',
str_contains($contentType, 'png') => 'png',
str_contains($contentType, 'gif') => 'gif',
str_contains($contentType, 'webp') => 'webp',
default => 'bin',
};
$filename = bin2hex(random_bytes(16)) . '.' . $ext;
$saveDir = __DIR__ . '/uploads/' . date('Y/m/d/');
if (!is_dir($saveDir)) mkdir($saveDir, 0755, true);
$savePath = $saveDir . $filename;
// 4. 寫入檔案(原子寫入:臨時檔 + rename)
$tmpPath = $savePath . '.tmp';
$bytes = file_put_contents($tmpPath, $raw, LOCK_EX);
if ($bytes === false || $bytes !== strlen($raw)) {
@unlink($tmpPath);
http_response_code(500);
exit('Write failed');
}
rename($tmpPath, $savePath);
// 5. 回傳結果
header('Content-Type: application/json');
echo json_encode([
'success' => true,
'path' => $savePath,
'url' => '/uploads/' . date('Y/m/d/') . $filename,
'size' => $bytes,
'mime' => $contentType,
]);
?>
// JavaScript
async function uploadBlob(blob) {
const res = await fetch('/upload_raw.php', {
method: 'POST',
headers: {'Content-Type': blob.type}, // 如 image/png
body: blob
});
return res.json();
}
// Canvas 導出上傳
canvas.toBlob(blob => uploadBlob(blob), 'image/png', 0.9);
<?php
if (str_starts_with($raw, 'data:image/')) {
// data:image/png;base64,iVBORw0K...
[$meta, $b64] = explode(',', $raw, 2);
$raw = base64_decode($b64);
if ($raw === false) exit('Invalid base64');
// 從 meta 解析 mime: preg_match('/data:(image\/\w+);base64/', $meta, $m)
}
?>
掌握原始流讀取,即可支援 Canvas 截圖上傳、WebRTC 截幀、IoT 設備直傳等非表單場景。