DIV CSS 佈局教程網

SpringMVC 搭配 jQuery Form 的 Ajax 檔案上傳實作
編輯:關於JavaScript     

專案要上傳檔案,以往都用整表單提交,畫面會跳一次。改試 jQuery Form 外掛的 ajaxSubmit 之後體驗好很多,這裡把設定與後端程式一起記下來。

準備工作

下載 jquery-form.js,並加入以下兩個 jar:

commons-fileupload-1.1.1.jar
commons-io-1.3.2.jar

Spring 設定 multipartResolver

在 spring-servlet.xml 中宣告,這一步是必要的,少了它檔案不會被解析:

<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
  <property name="defaultEncoding" value="utf-8" />
  <property name="maxUploadSize" value="10485760000" />
  <property name="maxInMemorySize" value="40960" />
</bean>

maxUploadSize 這裡設得相當寬鬆,實際專案請依需求收緊,避免被大量檔案塞爆磁碟。

頁面

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "https://www.w3.org/TR/html4/loose.dtd">
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" session="false" %>
<html>
<head>
<title>匯入</title>
<meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
<script src="<%=request.getContextPath()%>/common/nui/nui.js" type="text/javascript"></script>
<script src="<%=request.getContextPath()%>/common/nui/jquery/jquery-form.js" type="text/javascript"></script>
<script type="text/javascript" src="<%=request.getContextPath()%>/page4nui/master/projecttype/js/projecttype_import.js"></script>
<script type="text/javascript">
  var contextPath = "<%=request.getContextPath()%>";
</script>
</head>
<body>
<div id="test" class="nui-fit" style="padding-top:5px;min-width:300px;min-height:180px;">
  <form id="fileUpload" method="post" enctype="multipart/form-data">
    <div id="dataImport" style="width:100%;overflow:hidden;">
      <table style="width:100%;table-layout:fixed;" class="nui-form-table">
        <tr>
          <th align="right" style="width:25%">選擇文件:</th>
          <td>
            <input id="uploadFile" type="file" name="file" style="width:90%;">
            <font style="color:red;width:5%;"> *</font>
          </td>
        </tr>
      </table>
    </div>
    <div style="width:100%;padding-top:10px;" align="center">
      <input style="width:60px;" iconCls="icon-ok" value="確定" type="submit" />
      <span style="display:inline-block;width:25px;"></span>
      <a class="nui-button" iconCls="icon-cancel" style="width:60px;" onclick="cancel">取消</a>
    </div>
  </form>
</div>
</body>
</html>

核心 JavaScript

var msg;
$(function () {
  nui.parse();

  var options = {
    url: contextPath + "/webapp/cfProjectType/importExcel",
    beforeSubmit: showRequest,   // 送出前的處理
    success: showResponse,       // 完成後的處理
    resetForm: true,
    dataType: 'json'
  };

  $('#fileUpload').submit(function () {
    $(this).ajaxSubmit(options);
    return false;                // 阻擋表單預設行為,避免 dialog 自動關閉
  });
});

// 成功回呼
function showResponse(e) {
  nui.hideMessageBox(msg);
  if (e.importFlag == true) {
    CloseWindow("ok");
  } else {
    // 依回傳內容處理錯誤訊息
  }
}

// 送出前校驗
function showRequest(formData, jqForm, options) {
  if (formData[0].value == "" || formData[0].value == null) {
    nui.alert("請選擇文件");
    return false;
  }
  var fileName = $("#uploadFile").val().split("\\").pop();
  var strs = fileName.split('.');
  var suffix = strs[strs.length - 1];
  if (suffix != 'xls' && suffix != 'xlsx') {
    nui.alert("請選擇 excel 文件!");
    return false;
  }
  msg = nui.loading("Loading", "Please waiting");
}

後端 Java

@SuppressWarnings("unchecked")
@RequestMapping("/webapp/cfProjectType/importExcel")
@ResponseBody
public Map<String, Object> importExcel(@RequestParam("file") MultipartFile[] files,
                                      HttpServletRequest request) throws Throwable {
    InputStream fis = null;
    File fileIn = null;
    try {
        for (MultipartFile myfile : files) {
            if (!myfile.isEmpty()) {
                String realPath = request.getSession().getServletContext().getRealPath("/export");
                fileIn = new File(realPath);
                // 目錄不存在就建立
                if (!fileIn.exists() && !fileIn.isDirectory()) {
                    fileIn.mkdirs();
                }
                // 把上傳的檔案寫入資料夾
                myfile.transferTo(new File(realPath, myfile.getOriginalFilename()));
            }
        }
    } finally {
        if (fis != null) {
            fis.close();
        }
    }
    // 這裡接續你的匯入邏輯,並回傳結果
    return null;
}

除了 transferTo,用 FileUtils.copyInputStreamToFile(InputStream, File) 也能達到同樣效果。

三個安全提醒

檔名不可信:範例中把上傳檔名直接串進路徑,攻擊者可以藉 ../ 造成路徑穿越。實務上請自行產生檔名(例如 UUID 加副檔名),不要沿用使用者提供的名稱。

副檔名不足以驗證型別:副檔名可以偽造,建議同時檢查 content type 並比對檔頭簽章。

存檔位置:把使用者上傳的檔案存進 web 目錄底下有風險,最好放在容器外的專用目錄,並以程式控管存取權限。

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