原理:<form target="hidden_iframe"> 提交至隱藏 <iframe name="hidden_iframe">,伺服器回傳 JavaScript 呼叫 parent.callback(data) 通知父頁面。缺點:無法獲取上傳進度、錯誤處理困難、需輪詢 iframe 載入事件。
<!-- HTML -->
<input type="file" id="fileInput" multiple accept="image/*">
<progress id="progress" value="0" max="100" hidden></progress>
<div id="list"></div>
<script>
document.getElementById('fileInput').addEventListener('change', async (e) => {
const files = e.target.files;
const progress = document.getElementById('progress');
const list = document.getElementById('list');
for (const file of files) {
const formData = new FormData();
formData.append('file', file);
try {
// 使用 XMLHttpRequest 取得上傳進度
await new Promise((resolve, reject) => {
const xhr = new XMLHttpRequest();
xhr.open('POST', 'upload_ajax.php');
xhr.upload.onprogress = (evt) => {
if (evt.lengthComputable) {
progress.hidden = false;
progress.value = (evt.loaded / evt.total) * 100;
}
};
xhr.onload = () => {
if (xhr.status >= 200 && xhr.status < 300) resolve(JSON.parse(xhr.responseText));
else reject(new Error(xhr.statusText));
};
xhr.onerror = () => reject(new Error('Network error'));
xhr.send(formData);
});
list.insertAdjacentHTML('beforeend', `✅ ${file.name} 上傳成功`);
} catch (err) {
list.insertAdjacentHTML('beforeend', `❌ ${file.name}: ${err.message}`);
}
}
progress.hidden = true;
});
</script>
<?php
header('Content-Type: application/json; charset=utf-8');
$allowed = ['image/jpeg','image/png','image/gif','image/webp'];
$maxSize = 10 * 1024 * 1024;
$dir = __DIR__ . '/uploads/' . date('Y-m-d') . '/';
!is_dir($dir) && mkdir($dir, 0775, true);
$file = $_FILES['file'] ?? null;
if (!$file || $file['error'] !== UPLOAD_ERR_OK) {
echo json_encode(['error' => '上傳失敗: ' . ($file['error'] ?? '無檔案')]);
exit;
}
if ($file['size'] > $maxSize) {
echo json_encode(['error' => '檔案過大']);
exit;
}
$finfo = finfo_open(FILEINFO_MIME_TYPE);
$mime = finfo_file($finfo, $file['tmp_name']);
finfo_close($finfo);
if (!in_array($mime, $allowed)) {
echo json_encode(['error' => '型別不允許']);
exit;
}
$ext = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION));
$name = bin2hex(random_bytes(10)) . '.' . $ext;
if (move_uploaded_file($file['tmp_name'], $dir . $name)) {
echo json_encode(['success' => true, 'url' => 'uploads/' . date('Y-m-d') . '/' . $name]);
} else {
echo json_encode(['error' => '儲存失敗']);
}
?>
Blob.slice() 切片、SparkMD5 計算雜湊、Web Worker 並行Range 續傳| 特性 | iframe 方案 | XHR + FormData | Fetch + FormData |
|---|---|---|---|
| 上傳進度 | ❌ | ✅ xhr.upload.onprogress | ❌ (需 Stream API) |
| 錯誤處理 | 困難 | 完整 | 完整 |
| IE 相容 | IE8+ | IE10+ | Edge 14+ |
| 程式碼複雜度 | 高 | 中 | 低 |
| 推薦度 | 僅舊專案維護 | 需進度條時 | 現代專案首選 |