1. 程式人生 > >jQuery jForm ajax 單擊選中檔案直接自動上載 無需提交按鈕

jQuery jForm ajax 單擊選中檔案直接自動上載 無需提交按鈕

利用 jQuery 外掛 jform 實現檔案選中直接上載,無需點提交按鈕,完整例項如下:

外掛來自 https://github.com/malsup/form/

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script type="text/javascript" src="scripts/jquery/jquery/2.1.4/jquery.min.js"></script>
<script type="text/javascript" src="scripts/jquery/jform/jquery.form.js"></script>
<title>jForm Demo</title>
</head>
<body>
	<div id="ClickMe" style="cursor: pointer; width: 100px; height: 25px; background-color: #00ff00; border-radius: 5px;">Click Me!</div>
	<form id="formUpload" name="formUploadFile" method="POST" enctype="multipart/form-data">
		<input id="fileUpload" type="file" name="upload" style="display: none" />
	</form>
</body>
<script type="text/javascript">
  // form 內的檔案選擇內容被改變則立即提交
  $('#fileUpload').on('change', function()
  {
    // 當 file 框內容改變則提交 form
    $('#formUpload').submit();
    console.log('formUpload to submit');
  });

  // 定義的熱點被單擊則開啟檔案選擇框
  $('#ClickMe').on('click', function()
  {
    UploadFileOnSelect();
    console.log('object on click');
  });

  // 選需要上載的圖片 上載完畢清除 form
  function UploadFileOnSelect()
  {
    // 開啟檔案選擇框
    console.log('select file');
    var input = document.getElementById("fileUpload");
    input.click();
    // 提交完畢後初始化 form
    $('#formUpload').resetForm();
    console.log('selected file ' + input.value);
  }

  // jquery.form upload
  $('#formUpload').ajaxForm({
    // 設定返回格式
    dataType : 'json',
    // 接收檔案的 struts2 action 或者是 servlet 路徑
    url : '/struts/uploadMultfile',
    success : function(data)
    {
      // 返回成功資訊
      console.log('success: ' + data);
    },
    uploadProgress : function(event, position, total, percentComplete)
    {
      // 實時進度
      console.log('uploadProgress: ', percentComplete + '%', position, 'max:', total);
    },
    error : function(data)
    {
      // 返回錯誤資訊
      console.log('error: ' + data);
    }
  });
</script>
</html>

以下是基於 Google Chrome 的除錯資訊:


另一個上傳元件的使用(推薦):

http://blog.csdn.net/joyous/article/details/52643269

Q群討論 236201801

.