HTML4/IE9- 不支援 `FormData` + `XMLHttpRequest` Level 2。利用 **隱藏 `
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>偽 AJAX 圖片上傳 Demo</title>
<style>
body { font-family: sans-serif; padding: 20px; }
#picshow { margin-top: 15px; }
.hidden { display: none; }
</style>
</head>
<body>
<h3>選擇圖片上傳</h3>
<input type="file" name="file" id="fileInput" accept="image/*">
<div id="picshow"></div>
<!-- 隱藏 iframe -->
<iframe id="uploadFrame" name="uploadFrame" class="hidden"></iframe>
<script>
(function() {
var input = document.getElementById('fileInput');
var frame = document.getElementById('uploadFrame');
var showDiv = document.getElementById('picshow');
// 建立 form 動態提交
input.addEventListener('change', function() {
if (!this.files.length) return;
var form = document.createElement('form');
form.method = 'POST';
form.enctype = 'multipart/form-data';
form.action = 'upload.php'; // 後端處理
form.target = 'uploadFrame';
form.style.display = 'none';
// 複製 file input 到 form (避免原 input 被移動)
var clone = this.cloneNode(true);
this.parentNode.replaceChild(clone, this);
input = clone; // 更新參考
form.appendChild(this);
document.body.appendChild(form);
form.submit();
document.body.removeChild(form);
});
// 全域回調函式 (伺服器端呼叫)
window.uploadCallback = function(url, error) {
showDiv.innerHTML = '';
if (error) {
showDiv.innerHTML = '<span style="color:red">上傳失敗:' + error + '</span>';
return;
}
var img = document.createElement('img');
img.src = url;
img.style.maxWidth = '300px';
img.style.border = '1px solid #ddd';
showDiv.appendChild(img);
};
})();
</script>
</body>
</html>
<?php
header('Content-Type: text/html; charset=utf-8');
$allowed = ['image/jpeg', 'image/png', 'image/gif', 'image/webp'];
$maxSize = 5 * 1024 * 1024; // 5MB
$uploadDir = __DIR__ . '/uploads/';
if (!is_dir($uploadDir)) mkdir($uploadDir, 0755, true);
if (!isset($_FILES['file']) || $_FILES['file']['error'] !== UPLOAD_ERR_OK) {
echo '<script>parent.uploadCallback("", "無效的檔案上傳");</script>';
exit;
}
$finfo = finfo_open(FILEINFO_MIME_TYPE);
$mime = finfo_file($finfo, $_FILES['file']['tmp_name']);
finfo_close($finfo);
if (!in_array($mime, $allowed)) {
echo '<script>parent.uploadCallback("", "不支援的檔案類型");</script>';
exit;
}
if ($_FILES['file']['size'] > $maxSize) {
echo '<script>parent.uploadCallback("", "檔案過大 (限 5MB)");</script>';
exit;
}
$ext = ['image/jpeg'=>'jpg', 'image/png'=>'png', 'image/gif'=>'gif', 'image/webp'=>'webp'][$mime];
$filename = uniqid('img_', true) . '.' . $ext;
$dest = $uploadDir . $filename;
if (!move_uploaded_file($_FILES['file']['tmp_name'], $dest)) {
echo '<script>parent.uploadCallback("", "伺服器儲存失敗");</script>';
exit;
}
// 回傳可公開訪問的 URL
$publicUrl = '/uploads/' . $filename;
echo '<script>parent.uploadCallback("' . $publicUrl . '", "");</script>';
// 真 AJAX 上傳 (支援進度條)
var formData = new FormData();
formData.append('file', fileInput.files[0]);
$.ajax({
url: 'upload.php',
type: 'POST',
data: formData,
processData: false,
contentType: false,
xhr: function() {
var xhr = new window.XMLHttpRequest();
xhr.upload.addEventListener('progress', function(e) {
if (e.lengthComputable) {
var pct = (e.loaded / e.total * 100).toFixed(0);
$('#progress').text(pct + '%');
}
});
return xhr;
},
success: function(res) { /* ... */ }
});
| 方案 | 支援瀏覽器 | 進度條 | 複雜度 | 建議 |
|---|---|---|---|---|
| iframe 偽 AJAX | IE6+、所有舊瀏覽器 | ❌ | 低 | 維舊專案、內部系統 |
| FormData + XHR2 | IE10+、現代瀏覽器 | ✅ | 中 | **新專案首選** |
| fetch + FormData | 現代瀏覽器 (IE 不支援) | ✅ (ReadableStream) | 低 | 現代專案、PWA |
| Uppy / FilePond | 依底層支援 | ✅ 內建 UI | 高 (引入庫) | 複雜上傳需求 (分片、恢復、雲端直傳) |