DIV CSS 佈局教程網

用 iframe 模擬 Ajax 完成無刷新的檔案上傳
編輯:JavaScript綜合知識     

在 FormData 與 XHR2 普及之前,「不刷新頁面上傳檔案」的標準做法是動態造一個隱藏 iframe,讓表單把結果送回那個 frame,再由父頁接收。理解這個技巧有助於看懂許多老系統的實作。

前端:動態建立 iframe 與 form

<script>
window.onload = function () { upfile('file.php'); };

function upfile(url) {
  // 建立隱藏的 iframe 作為表單的提交目標
  var iframe = document.createElement("iframe");
  document.body.appendChild(iframe);
  iframe.id = 'iframeName';
  iframe.name = 'iframeName';
  iframe.style.display = 'none';

  // 建立 form,target 指向 iframe,因此不會刷新主頁
  var turnForm = document.createElement("form");
  document.body.appendChild(turnForm);
  turnForm.method = 'post';
  turnForm.action = url;
  turnForm.encoding = "multipart/form-data";   // 上傳檔案必須
  turnForm.name = 'formNamer';
  turnForm.target = 'iframeName';

  // 加入檔案欄位
  var newElement = document.createElement("input");
  newElement.setAttribute("name", "inputname");
  newElement.setAttribute("type", "file");
  turnForm.appendChild(newElement);
}

// 送出
function formSubmit() {
  document.formNamer.submit();
}

// 由後端回傳的 script 呼叫,接收結果
function callback(result) {
  if (result.error == 0) {
    document.getElementById('test').src = result.img[1] + '/' + result.img[2];
  } else {
    alert(result.meg);
  }
}
</script>

<a href="javascript:formSubmit()">上傳</a>
<img src="pasic.jpg" id="test" width="200" height="200">

關鍵在 target:表單的 submit 目標被導向 iframe,瀏覽器就不會整個頁面跳走,而 iframe 內載入的回應可以是一段 <script>parent.callback(...),藉此把資料交回父頁。注意 iframe 的 id 與 name 都要設,因為 IE 認 name、其他瀏覽器偏向 id。

後端:PHP 接收並回傳 callback

<?php
header("content-Type: text/html; charset=UTF-8");

if (@is_uploaded_file($_FILES['inputname']['tmp_name'])) {
  $f      = $_FILES['inputname'];
  $name   = $f["name"];
  $size   = $f["size"];
  $type   = $f["type"];
  $tmp    = $f["tmp_name"];
  $error  = $f["error"];

  $okType = in_array($type, ['image/jpg','image/jpeg','image/png','image/gif']);

  if ($okType) {
    $fileDir = dirname(__FILE__) . '/img/upfile' . time() . $name;
    $img = explode('/', $fileDir);
    move_uploaded_file($tmp, $fileDir);

    $data = ['img'=>$img, 'name'=>$name, 'type'=>$type,
             'size'=>$size, 'filename'=>$tmp, 'fileDir'=>$fileDir];

    $msgs = [
      1 => '超過了 php.ini 中 upload_max_filesize 的限制',
      2 => '超過了表單 MAX_FILE_SIZE 指定的值',
      3 => '檔案只有部分被上傳',
      4 => '沒有檔案被上傳',
    ];

    if ($error == 0) {
      $data['error'] = 0;
    } else {
      $data['error'] = $error;
      $data['meg']   = $msgs[$error] ?? '上傳失敗';
    }
    exit("<script>parent.callback(" . json_encode($data) . ");</script>");
  }
}
$data = ['error' => 4, 'meg' => '沒有檔案被上傳'];
exit("<script>parent.callback(" . json_encode($data) . ");</script>");

把四段 elseif 收進陣列對照,程式短了很多,訊息也好維護。這裡有幾個必須修正的安全問題:檔名直接沿用使用者上傳的名稱,可能包含 ../ 造成路徑穿越,也可能覆蓋既有檔案,請改用 time() 加隨機字串自行命名;副檔名比 MIME 更不可靠,最好用 getimagesize() 或 finfo 確認真的它是圖片;存檔目錄要禁止執行權限。另外回傳的 script 字串若把檔名等資料直接嵌入,需先 json_encode 並避免 </script> injection,用 addslashes 並不足夠。

今天的做法

var fd = new FormData();
fd.append("file", input.files[0]);
fetch("upload.php", { method: "POST", body: fd })
  .then(r => r.json())
  .then(callback);

XMLHttpRequest 或 fetch 搭配 FormData 只要幾行就能上傳,還能拿到進度條(xhr.upload.onprogress),不必再借道 iframe。iframe 這招今天主要價值在於維護舊專案,以及作為不支援 XHR 的環境下的後備方案。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved