<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>iframe AJAX 上傳 Demo</title>
</head>
<body>
<h3>檔案上傳 (iframe 方式)</h3>
<form action="b.php" method="post" enctype="multipart/form-data" target="uploadFrame">
<input type="file" name="userfile" id="userfile" required>
<button type="submit">上傳</button>
<span id="msg" style="margin-left:10px; color:#666;"></span>
</form>
<iframe name="uploadFrame" id="uploadFrame" style="display:none;"></iframe>
<script>
// 全域回調函數
window.uploadCallback = function(success, message, fileUrl) {
var $msg = $('#msg');
if (success) {
$msg.text('上傳成功:' + message).css('color', 'green');
// 可選:顯示縮略圖
if (fileUrl) {
$('
').attr('src', fileUrl).css('max-width','200px').insertAfter($msg);
}
} else {
$msg.text('上傳失敗:' + message).css('color', 'red');
}
};
</script>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
</body>
</html>
<?php
header('Content-Type: text/html; charset=utf-8');
$uploadDir = __DIR__ . '/uploads/';
if (!is_dir($uploadDir)) mkdir($uploadDir, 0755, true);
$allowed = ['image/jpeg', 'image/png', 'image/gif', 'image/webp'];
$maxSize = 5 * 1024 * 1024;
$success = false;
$message = '未知錯誤';
$fileUrl = '';
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_FILES['userfile'])) {
$file = $_FILES['userfile'];
if ($file['error'] === UPLOAD_ERR_OK) {
$finfo = finfo_open(FILEINFO_MIME_TYPE);
$mime = finfo_file($finfo, $file['tmp_name']);
finfo_close($finfo);
if (in_array($mime, $allowed) && $file['size'] <= $maxSize) {
$ext = ['image/jpeg'=>'jpg','image/png'=>'png','image/gif'=>'gif','image/webp'=>'webp'][$mime];
$name = uniqid('up_', true) . '.' . $ext;
$dest = $uploadDir . $name;
if (move_uploaded_file($file['tmp_name'], $dest)) {
$success = true;
$message = '檔案已儲存';
$fileUrl = '/uploads/' . $name;
} else {
$message = '伺服器寫入失敗';
}
} else {
$message = '檔案類型或大小不符合要求';
}
} else {
$message = '上傳錯誤代碼: ' . $file['error'];
}
}
// 輸出執行父頁回調的 JavaScript
echo '';
?>
| 問題 | 解決 |
|---|---|
| 表單提交後頁面跳轉 | 確保 ` |
| 回調不執行 | 檢查後端 `Content-Type: text/html`、輸出完整 `` |
| 跨域失效 | 父頁與後端**必須同域** (協議/域名/埠),否則 `parent` 存取被阻擋 |
| 重複提交 | 提交後禁用按鈕、顯示 loading、或用 token 防重複 |
| IE 快取 iframe 回應 | 後端輸出 `header('Cache-Control: no-cache, must-revalidate')` |
| 中文檔名亂碼 | PHP `move_uploaded_file` 使用英文隨機檔名,資料庫記錄原始檔名 |
const form = document.querySelector('form');
form.addEventListener('submit', async (e) => {
e.preventDefault();
const formData = new FormData(form);
try {
const resp = await fetch('b.php', { method: 'POST', body: formData });
const result = await resp.json(); // 後端改回傳 JSON
if (result.success) { /* 成功處理 */ }
} catch (err) { /* 錯誤處理 */ }
});
iframe 形式 AJAX 是**過渡時期**的產物,現代專案請直接使用 **`fetch` + `FormData`** 或成熟庫 (Uppy、FilePond、Dropzone)。僅在必須支援 IE9 以下、且無法引入 Polyfill 時使用本文方案。