DIV CSS 佈局教程網

用 ajaxfileupload.js 實作 Ajax 檔案上傳(PHP 版)
編輯:關於JavaScript     

無論 PHP 或其他後端語言,都內建了檔案上傳功能,實作起來並不難。搭配 JavaScript,就能做出 Ajax 式的檔案上傳體驗。jQuery 本身沒有提供對應的簡化函式,但社群有不少外掛可用。其中 Phpletter.com 提供的 ajaxfileupload.js 相當輕量,寫法又與 jQuery 的全域方法 $.post() 類似,簡單易用。

不過它實在太簡潔了——除了上傳檔案的路徑,無法傳送額外的值到後端。因此我改造了這個腳本,加上一個 data 物件參數。

一、原理

這裡以 PHP 作為後端腳本。幾乎每本 PHP 書都會提到用 move_uploaded_file() 上傳檔案,這部分不再贅述;重點在 Ajax 的實作方式。

由於一直在用 jQuery,直覺反應是試 $.post(),用選擇器取出 file 輸入框的 value 再送到後端。實測證明這行不通——檔案內容無法用這種方式傳送。

回到正題。要實現 Ajax 上傳,最經典的做法是隱藏 iframe:這也是在不使用 JavaScript 特殊 API 的情況下,實現「不刷新頁面上傳」的常見手段。ajaxfileupload.js 正是走這條路——先用 jQuery 選擇器取得 file 欄位中的檔案路徑,接著動態建立一個 iframe,在其中放入新的 file 欄位,以 post 方式提交到後端,最後把結果回傳前台。

二、基本用法

前台 HTML:

<script type="text/javascript">
$("#buttonUpload").click(function () {
  $.ajaxFileUpload({
    url: 'doajaxfileupload.php',  // 處理上傳的後端
    secureuri: false,
    fileElementId: 'img',         // 與頁面中 file 欄位的 id 對應
    dataType: 'json',             // text、xml、json、html、script、jsonp 五種
    success: function (data) {
      alert(data.file_infor);
    }
  });
});
</script>

<input id="img" type="file" size="45" name="img" />
<button id="buttonUpload" onclick="return ajaxFileUpload();">Upload</button>

後端 doajaxfileupload.php:

<?php
$upFilePath = "../attachment/";
$ok = @move_uploaded_file($_FILES['img']['tmp_name'], $upFilePath);
if ($ok === FALSE) {
  echo json_encode('file_infor' => '上傳失敗');
} else {
  echo json_encode('file_infor' => '上傳成功');
}
?>

想除錯時,可以先把收到的變數存成檔案看看內容:

$file_info = var_export($_FILES, true);
$ok = file_put_contents("../attachment/file_info.txt", $file_info);
if ($ok) exit(json_encode('file_infor' => '上傳成功'));
exit(json_encode('file_infor' => '上傳失敗'));

※ 注意:檔案欄位的兩個屬性缺一不可,也不能混淆。

1. id='img' 供外掛的 fileElementId:'img' 識別,jQuery 選擇器靠它取值;
2. name='img' 是 post 到後端時 PHP 讀取 $_FILES['img'] 的依據,少了它 $_FILES 會是空的。

三、支援額外參數

有時後端需要依據某些變數決定如何處理上傳的檔案(例如更新而非新增)。為此我修改了外掛:

addOtherRequestsToForm: function (form, data) {
  // 加入額外參數
  var originalElement = $('<input type="hidden" name="" value="">');
  for (var key in data) {
    name = key;
    value = data[key];
    var cloneElement = originalElement.clone();
    cloneElement.attr({'name': name, 'value': value});
    $(cloneElement).appendTo(form);
  }
  return form;
},

ajaxFileUpload: function (s) {
  s = jQuery.extend({}, jQuery.ajaxSettings, s);
  var id = new Date().getTime()
  var form = jQuery.createUploadForm(id, s.fileElementId);
  if (s.data) form = jQuery.addOtherRequestsToForm(form, s.data);
  var io = jQuery.createUploadIframe(id, s.secureuri);
  // ...
}

於是前台就能這樣傳額外參數:

url: 'doajaxfileupload.php',
secureuri: false,
data: {'test': 'test', 'ok': 'ok'}, // 以物件方式傳遞,值可以是 JavaScript 變數
fileElementId: 'img',

後端處理:

array_push($_FILES, $_REQUEST);
$file_info = var_export($_FILES, true);
$ok = file_put_contents("../attachment/file_info.txt", $file_info);
if ($ok) exit(json_encode('file_infor' => '上傳成功'));
exit(json_encode('file_infor' => '上傳失敗'));

可見原理很單純:把額外的 data 物件內容一併加進 iframe 下的 form,一起送到後端,再用 $_REQUEST 取得這些值。輸出記錄如下:

array (
  'file' =>
  array (
    'name' => 'firefox-java.txt',
    'type' => 'text/plain',
    'tmp_name' => 'D:\\Tools\\xampp\\tmp\\phpED45.tmp',
    'error' => 0,
    'size' => 250,
  ),
  0 =>
  array (
    'test' => 'test',
    'ok' => 'ok',
    'PHPSESSID' => 'e379fd4fb2abca6e802a1302805a5535',
  ),
)

ajaxfileupload.js 原始碼

jQuery.extend({
  createUploadIframe: function (id, uri) {
    // 建立 frame
    var frameId = 'jUploadFrame' + id;
    if (window.ActiveXObject) {
      var io = document.createElement('<iframe id="' + frameId + '" name="' + frameId + '" />');
      if (typeof uri == 'boolean') {
        io.src = 'javascript:false';
      } else if (typeof uri == 'string') {
        io.src = uri;
      }
    } else {
      var io = document.createElement('iframe');
      io.id = frameId;
      io.name = frameId;
    }
    io.style.position = 'absolute';
    io.style.top = '-1000px';
    io.style.left = '-1000px';
    document.body.appendChild(io);
    return io;
  },

  createUploadForm: function (id, fileElementId) {
    // 建立 form
    var formId = 'jUploadForm' + id;
    var fileId = 'jUploadFile' + id;
    var form = $('<form action="" method="POST" name="' + formId + '" id="' + formId + '" enctype="multipart/form-data"></form>');
    var oldElement = $('#' + fileElementId);
    var newElement = $(oldElement).clone();
    $(oldElement).attr('id', fileId);
    $(oldElement).before(newElement);
    $(oldElement).appendTo(form);
    $(form).css('position', 'absolute');
    $(form).css('top', '-1200px');
    $(form).css('left', '-1200px');
    $(form).appendTo('body');
    return form;
  },

  addOtherRequestsToForm: function (form, data) {
    // 加入額外參數
    var originalElement = $('<input type="hidden" name="" value="">');
    for (var key in data) {
      name = key;
      value = data[key];
      var cloneElement = originalElement.clone();
      cloneElement.attr({'name': name, 'value': value});
      $(cloneElement).appendTo(form);
    }
    return form;
  },

  ajaxFileUpload: function (s) {
    s = jQuery.extend({}, jQuery.ajaxSettings, s);
    var id = new Date().getTime()
    var form = jQuery.createUploadForm(id, s.fileElementId);
    if (s.data) form = jQuery.addOtherRequestsToForm(form, s.data);
    var io = jQuery.createUploadIframe(id, s.secureuri);
    var frameId = 'jUploadFrame' + id;
    var formId = 'jUploadForm' + id;

    if (s.global && !jQuery.active++) {
      jQuery.event.trigger("ajaxStart");
    }
    var requestDone = false;
    var xml = {};
    if (s.global) jQuery.event.trigger("ajaxSend", [xml, s]);

    // 等待回應
    var uploadCallback = function (isTimeout) {
      var io = document.getElementById(frameId);
      try {
        if (io.contentWindow) {
          xml.responseText = io.contentWindow.document.body ? io.contentWindow.document.body.innerHTML : null;
          xml.responseXML = io.contentWindow.document.XMLDocument ? io.contentWindow.document.XMLDocument : io.contentWindow.document;
        } else if (io.contentDocument) {
          xml.responseText = io.contentDocument.document.body ? io.contentDocument.document.body.innerHTML : null;
          xml.responseXML = io.contentDocument.document.XMLDocument ? io.contentDocument.document.XMLDocument : io.contentDocument.document;
        }
      } catch (e) {
        jQuery.handleError(s, xml, null, e);
      }
      if (xml || isTimeout == "timeout") {
        requestDone = true;
        var status;
        try {
          status = isTimeout != "timeout" ? "success" : "error";
          if (status != "error") {
            var data = jQuery.uploadHttpData(xml, s.dataType);
            if (s.success) s.success(data, status);
            if (s.global) jQuery.event.trigger("ajaxSuccess", [xml, s]);
          } else {
            jQuery.handleError(s, xml, status);
          }
        } catch (e) {
          status = "error";
          jQuery.handleError(s, xml, status, e);
        }
        if (s.global) jQuery.event.trigger("ajaxComplete", [xml, s]);
        if (s.global && !--jQuery.active) jQuery.event.trigger("ajaxStop");
        if (s.complete) s.complete(xml, status);

        jQuery(io).unbind()
        setTimeout(function () {
          try {
            $(io).remove();
            $(form).remove();
          } catch (e) {
            jQuery.handleError(s, xml, null, e);
          }
        }, 100)
        xml = null;
      }
    }

    // 逾時檢查
    if (s.timeout > 0) {
      setTimeout(function () {
        if (!requestDone) uploadCallback("timeout");
      }, s.timeout);
    }

    try {
      var form = $('#' + formId);
      $(form).attr('action', s.url);
      $(form).attr('method', 'POST');
      $(form).attr('target', frameId);
      if (form.encoding) {
        form.encoding = 'multipart/form-data';
      } else {
        form.enctype = 'multipart/form-data';
      }
      $(form).submit();
    } catch (e) {
      jQuery.handleError(s, xml, null, e);
    }

    if (window.attachEvent) {
      document.getElementById(frameId).attachEvent('onload', uploadCallback);
    } else {
      document.getElementById(frameId).addEventListener('load', uploadCallback, false);
    }
    return { abort: function () {} };
  },

  uploadHttpData: function (r, type) {
    var data = !type;
    data = type == "xml" || data ? r.responseXML : r.responseText;
    if (type == "script") jQuery.globalEval(data);
    if (type == "json") eval("data = " + data);
    if (type == "html") jQuery("<div>").html(data).evalScripts();
    return data;
  }
})

今日觀點

iframe 上傳是它那個年代的標準解法,但它有明顯限制:無法得知上傳進度、回應的 JSON 需要透過 eval 解析(有安全風險)。若你今天才要實作檔案上傳,直接用 XMLHttpRequest 的 FormData 搭配 upload.onprogress 會乾淨得多,也不必再依賴 jQuery 外掛。

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