在不支援 FormData + XMLHttpRequest Level 2 的舊瀏覽器(IE9 及以下)中,利用 隱藏 iframe 作為 form target,實現「無刷新」上傳體驗。流程:
<iframe name="upload_iframe"> 並隱藏<form target="upload_iframe" enctype="multipart/form-data"><input type="file"> 移入 form 或動態創建<script>parent.callback(...)</script> 跨域通知父頁callback 處理結果,清理 DOM/**
* Iframe 無刷新上傳核心類
*/
class IframeUploader {
constructor(options = {}) {
this.url = options.url || '/upload';
this.fileInputId = options.fileInputId || 'fileInput';
this.onProgress = options.onProgress || (() => {});
this.onSuccess = options.onSuccess || (() => {});
this.onError = options.onError || (() => {});
this.iframeName = 'upload_iframe_' + Date.now();
this.formName = 'upload_form_' + Date.now();
this._initIframe();
this._initForm();
}
_initIframe() {
this.iframe = document.createElement('iframe');
this.iframe.name = this.iframeName;
this.iframe.id = this.iframeName;
this.iframe.style.display = 'none';
document.body.appendChild(this.iframe);
// 監聽 iframe 載入完成(兼容 IE)
this.iframe.onload = this.iframe.onreadystatechange = () => {
if (this.iframe.readyState && this.iframe.readyState !== 'complete') return;
this._handleResponse();
};
}
_initForm() {
this.form = document.createElement('form');
this.form.name = this.formName;
this.form.id = this.formName;
this.form.method = 'POST';
this.form.action = this.url;
this.form.enctype = 'multipart/form-data'; // 必須
this.form.target = this.iframeName;
this.form.style.display = 'none';
document.body.appendChild(this.form);
// 綁定現有 file input 或創建新的
const fileInput = document.getElementById(this.fileInputId);
if (fileInput) {
// 複製一份避免移動原節點導致表單重置問題
this.fileInput = fileInput.cloneNode(true);
this.fileInput.name = 'file'; // 後端接收字段名
this.form.appendChild(this.fileInput);
}
}
upload(file) {
if (file) {
// 若傳入 File 對象,需構造 DataTransfer(現代瀏覽器)
// 這裡簡化:假設 fileInput 已由用戶選擇
}
this.form.submit();
this.onProgress(0); // 偽進度
}
_handleResponse() {
try {
const doc = this.iframe.contentDocument || this.iframe.contentWindow.document;
const text = doc.body.innerText || doc.body.textContent;
// 後端約定返回 JSON 字串
const result = JSON.parse(text);
if (result.success) {
this.onSuccess(result.data);
} else {
this.onError(result.message);
}
} catch (e) {
this.onError('解析回應失敗: ' + e.message);
} finally {
this.destroy();
}
}
destroy() {
if (this.iframe) this.iframe.remove();
if (this.form) this.form.remove();
}
}
// 使用示例
const uploader = new IframeUploader({
url: '/api/upload',
fileInputId: 'fileInput',
onSuccess: (data) => {
console.log('上傳成功', data);
document.getElementById('preview').src = data.url;
},
onError: (msg) => alert('上傳失敗: ' + msg)
});
document.getElementById('btnUpload').onclick = () => uploader.upload();
<?php
header('Content-Type: application/json; charset=utf-8');
$allowedTypes = ['image/jpeg', 'image/png', 'image/gif', 'image/webp'];
$maxSize = 5 * 1024 * 1024; // 5MB
$response = ['success' => false, 'message' => '', 'data' => null];
if (!isset($_FILES['file']) || $_FILES['file']['error'] !== UPLOAD_ERR_OK) {
$response['message'] = '無文件或上傳錯誤: ' . $_FILES['file']['error'];
echo json_encode($response);
exit;
}
$file = $_FILES['file'];
if (!in_array($file['type'], $allowedTypes)) {
$response['message'] = '不支援的文件類型: ' . $file['type'];
echo json_encode($response);
exit;
}
if ($file['size'] > $maxSize) {
$response['message'] = '文件過大,限制 5MB';
echo json_encode($response);
exit;
}
$ext = pathinfo($file['name'], PATHINFO_EXTENSION);
$newName = uniqid('img_') . '.' . $ext;
$destPath = __DIR__ . '/uploads/' . $newName;
if (!is_dir(dirname($destPath))) {
mkdir(dirname($destPath), 0755, true);
}
if (move_uploaded_file($file['tmp_name'], $destPath)) {
$response['success'] = true;
$response['data'] = [
'url' => '/uploads/' . $newName,
'name' => $file['name'],
'size' => $file['size'],
'type' => $file['type']
];
} else {
$response['message'] = '文件保存失敗';
}
echo json_encode($response);
| 方案 | 支援瀏覽器 | 進度條 | 複雜度 | 推薦度 |
|---|---|---|---|---|
| iframe + form | IE6+ | 無(偽) | 中 | ⭐⭐(僅維護舊專案) |
| FormData + XHR2 | IE10+ | 原生支援 | 低 | ⭐⭐⭐⭐⭐ |
| fetch + FormData | 現代瀏覽器 | 需 ReadableStream | 低 | ⭐⭐⭐⭐ |
| axios / 上傳組件 | 視打包目標 | 完善 | 低 | ⭐⭐⭐⭐⭐ |
iframe 上傳是「上古時代」的產物,理解其原理有助於維護老專案。新專案**強烈建議**直接使用 FormData + fetch/axios,獲得真實進度、更好的錯誤處理與程式碼可維護性。若必須支援 IE9,可引入 iframe-transport 類庫封裝兼容層。