萬盛學電腦網

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

PHP 接收原始 POST 二進制數據並保存為圖片檔案

前端通過 `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://input` 只能讀一次,不可重複 `file_get_contents`;需多次使用請先存變數。
  • 不依賴 `$_FILES`:`$_FILES` 僅在 `multipart/form-data` 時填充。
  • 大檔案流式處理:`$in = fopen('php://input','rb'); $out = fopen($path,'wb'); stream_copy_to_stream($in,$out);` 避免記憶體峰值。
  • 安全驗證:`getimagesizefromstring($raw)` 驗證真實圖片類型,防偽裝上傳。
  • 原子寫入:寫 `.tmp` 再 `rename()`,防止併發讀到半寫檔案。

擴展:支援 Base64 Data URI

<?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 設備直傳等非表單場景。

copyright © 萬盛學電腦網 all rights reserved