萬盛學電腦網

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

PHP 搭配 HTML5 FormData 實現表單與檔案非同步上傳

HTML5 FormData 介面讓前端能輕鬆序列化表單資料(含檔案),配合 fetch 或 XMLHttpRequest 即可實現無刷新提交。本文示範完整前後端流程:前端建構 FormData、發送請求;後端 PHP 接收、驗證、儲存檔案、回傳 JSON。

前端:建構與送出 FormData

方法一:自動收集表單(推薦)

<form id="uploadForm" enctype="multipart/form-data">
  <input type="text" name="username" placeholder="用戶名" required>
  <input type="email" name="email" placeholder="Email">
  <input type="file" name="avatar" accept="image/*" required>
  <button type="submit">上傳</button>
</form>

<script>
document.getElementById('uploadForm').addEventListener('submit', async (e) => {
  e.preventDefault();
  const form = e.target;
  const formData = new FormData(form); // 自動包含所有 name 屬性的欄位與檔案

  try {
    const resp = await fetch('upload.php', {
      method: 'POST',
      body: formData
      // 不要手動設定 Content-Type,瀏覽器會自動帶上 boundary
    });
    const result = await resp.json();
    if (result.success) {
      alert('上傳成功!檔案:' + result.filename);
    } else {
      alert('上傳失敗:' + result.message);
    }
  } catch (err) {
    console.error(err);
    alert('網路錯誤');
  }
});
</script>

方法二:手動組裝(靈活控制)

const formData = new FormData();
formData.append('username', 'john');
formData.append('avatar', fileInput.files[0], 'custom-name.jpg');
// 可動態新增、刪除、修改欄位

後端 PHP:接收、驗證、儲存

<?php
header('Content-Type: application/json; charset=utf-8');

$response = ['success' => false, 'message' => ''];

// 1. 基本驗證
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
  $response['message'] = '僅接受 POST 請求';
  echo json_encode($response);
  exit;
}

$username = isset($_POST['username']) ? trim($_POST['username']) : '';
if ($username === '') {
  $response['message'] = '用戶名不可為空';
  echo json_encode($response);
  exit;
}

// 2. 檔案處理
if (!isset($_FILES['avatar']) || $_FILES['avatar']['error'] !== UPLOAD_ERR_OK) {
  $response['message'] = '檔案上傳錯誤:' . ($_FILES['avatar']['error'] ?? '未上傳');
  echo json_encode($response);
  exit;
}

$file = $_FILES['avatar'];
$allowedTypes = ['image/jpeg', 'image/png', 'image/gif', 'image/webp'];
$finfo = finfo_open(FILEINFO_MIME_TYPE);
$mime = finfo_file($finfo, $file['tmp_name']);
finfo_close($finfo);

if (!in_array($mime, $allowedTypes)) {
  $response['message'] = '僅允許 JPG/PNG/GIF/WebP 圖片';
  echo json_encode($response);
  exit;
}

// 3. 安全儲存
$ext = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION));
$newName = 'avatar_' . $username . '_' . time() . '.' . $ext;
$destDir = __DIR__ . '/uploads/';
if (!is_dir($destDir)) mkdir($destDir, 0755, true);
$destPath = $destDir . $newName;

if (move_uploaded_file($file['tmp_name'], $destPath)) {
  $response['success'] = true;
  $response['filename'] = $newName;
  $response['path'] = '/uploads/' . $newName;
} else {
  $response['message'] = '伺服器儲存失敗';
}

echo json_encode($response);

進階主題

上傳進度顯示

使用 XMLHttpRequest 的 upload.onprogress 事件:

const xhr = new XMLHttpRequest();
xhr.upload.onprogress = (e) => {
  if (e.lengthComputable) {
    const percent = Math.round((e.loaded / e.total) * 100);
    progressBar.style.width = percent + '%';
  }
};
xhr.open('POST', 'upload.php');
xhr.send(formData);

多檔案上傳

<input type="file" name="photos[]" multiple>
// PHP 端 $_FILES['photos'] 為陣列結構,需迴圈處理

大檔案分片上傳

前端使用 Blob.slice() 切片,搭配 spark-md5 計算雜湊,後端合併分片。適合 GB 級檔案,斷點續傳。

安全性檢查清單

  • 驗證 MIME 型別(finfo),不可信任副檔名或 $_FILES['type']。
  • 限制檔案大小(php.ini upload_max_filesize、post_max_size;前端 JS 預檢)。
  • 儲存路徑置於 Web 根目錄外,或以 .htaccess 禁止腳本執行。
  • 檔案重新命名,避免覆蓋與路徑遍歷。
  • 採用 CSRF Token 保護表單提交。

總結

FormData + fetch 讓非同步檔案上傳變得極簡潔,配合 PHP 完善的 $_FILES 處理機制,即可構建安全、體驗良好的上傳功能。掌握進度顯示、多檔、分片等進階技巧,可滿足從頭像上傳到大檔傳輸的多樣需求。

copyright © 萬盛學電腦網 all rights reserved