萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 腳本程式專題 >> JavaScript

原生 JS 實現 iframe 無刷新文件上傳:完整前後端代碼詳解

原理概覽

在不支援 FormData + XMLHttpRequest Level 2 的舊瀏覽器(IE9 及以下)中,利用 隱藏 iframe 作為 form target,實現「無刷新」上傳體驗。流程:

  1. 動態創建 <iframe name="upload_iframe"> 並隱藏
  2. 動態創建 <form target="upload_iframe" enctype="multipart/form-data">
  3. 將 <input type="file"> 移入 form 或動態創建
  4. 提交 form,伺服器返回 <script>parent.callback(...)</script> 跨域通知父頁
  5. 父頁 callback 處理結果,清理 DOM

前端完整實現(原生 JS,無依賴)

/**
 * 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 示例(對應原文邏輯)

<?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 + formIE6+無(偽)中⭐⭐(僅維護舊專案)
FormData + XHR2IE10+原生支援低⭐⭐⭐⭐⭐
fetch + FormData現代瀏覽器需 ReadableStream低⭐⭐⭐⭐
axios / 上傳組件視打包目標完善低⭐⭐⭐⭐⭐

結語

iframe 上傳是「上古時代」的產物,理解其原理有助於維護老專案。新專案**強烈建議**直接使用 FormData + fetch/axios,獲得真實進度、更好的錯誤處理與程式碼可維護性。若必須支援 IE9,可引入 iframe-transport 類庫封裝兼容層。

copyright © 萬盛學電腦網 all rights reserved