DIV CSS 佈局教程網

ajaxfileupload 非同步上傳:jQuery 搭配 Struts2 的完整實作
編輯:JQuery特效代碼     

專案需要處理檔案上傳,又不希望整頁刷新,就可以用 Jquery Ajax File Uploader 這個元件。它的下載網址為 https://www.phpletter.com/download_project_version.php?version_id=6,伺服器端本範例採用 Struts2 接收。

環境需求

  • jquery.js
  • ajaxfileupload.js
  • Struts2 依賴的 jar 包
  • struts2-json-plugin-2.1.8.1.jar

撰寫上傳用的 Action

package com.ajaxfile.action;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import org.apache.struts2.ServletActionContext;
import com.opensymphony.xwork2.ActionSupport;

@SuppressWarnings("serial")
public class FileAction extends ActionSupport {

  private File file;
  private String fileFileName;
  private String fileFileContentType;
  private String message = "你已成功上傳文件";

  public String getMessage() { return message; }
  public void setMessage(String message) { this.message = message; }
  public File getFile() { return file; }
  public void setFile(File file) { this.file = file; }
  public String getFileFileName() { return fileFileName; }
  public void setFileFileName(String fileFileName) { this.fileFileName = fileFileName; }
  public String getFileFileContentType() { return fileFileContentType; }
  public void setFileFileContentType(String fileFileContentType) {
    this.fileFileContentType = fileFileContentType;
  }

  @SuppressWarnings("deprecation")
  @Override
  public String execute() throws Exception {
    String path = ServletActionContext.getRequest().getRealPath("/upload");
    try {
      File f = this.getFile();
      if (this.getFileFileName().endsWith(".exe")) {
        message = "對不起,你上傳的文件格式不允許!!!";
        return ERROR;
      }
      FileInputStream inputStream = new FileInputStream(f);
      FileOutputStream outputStream =
        new FileOutputStream(path + "/" + this.getFileFileName());
      byte[] buf = new byte[1024];
      int length = 0;
      while ((length = inputStream.read(buf)) != -1) {
        outputStream.write(buf, 0, length);
      }
      inputStream.close();
      outputStream.flush();
    } catch (Exception e) {
      e.printStackTrace();
      message = "對不起,文件上傳失敗了!!!!";
    }
    return SUCCESS;
  }
}

struts.xml 設定

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.1//EN"
  "https://struts.apache.org/dtds/struts-2.1.dtd">
<struts>
  <package name="struts2" extends="json-default">
    <action name="fileUploadAction" class="com.ajaxfile.action.FileAction">
      <result type="json" name="success">
        <param name="contentType">text/html</param>
      </result>
      <result type="json" name="error">
        <param name="contentType">text/html</param>
      </result>
    </action>
  </package>
</struts>

contentType 參數一定要寫,否則瀏覽器會把回傳的 JSON 當成檔案提示另存,而不會交給 ajaxfileupload 處理。原因是 Struts2 JSON Plugin 預設的 contentType 是 application/json,而 ajaxfileupload 要求的是 text/html。這是本範例最容易卡住的一步。

上傳頁面

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
  "https://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>檔案上傳</title>
<script type="text/javascript" src="js/jquery.js"></script>
<script type="text/javascript" src="js/ajaxfileupload.js"></script>
<script type="text/javascript">
function ajaxFileUpload() {
  $("#loading")
    .ajaxStart(function () {
      $(this).show();      // 開始上傳時顯示 loading 圖
    })
    .ajaxComplete(function () {
      $(this).hide();      // 上傳完成後隱藏
    });

  $.ajaxFileUpload({
    url: 'fileUploadAction.action',   // 伺服器端接收位址
    secureuri: false,                 // 一般設為 false
    fileElementId: 'file',            // 檔案欄位的 id
    dataType: 'json',                 // 回傳值類型
    success: function (data, status) {
      alert(data.message);
      if (typeof (data.error) != 'undefined') {
        if (data.error != '') {
          alert(data.error);
        } else {
          alert(data.message);
        }
      }
    },
    error: function (data, status, e) {
      alert(e);
    }
  });
  return false;
}
</script>
</head>
<body>
<img src="loading.gif" id="loading" style="display: none;">
<input type="file" id="file" name="file" />
<br />
<input type="button" value="上傳" onclick="return ajaxFileUpload();">
</body>
</html>

幾個實作細節

注意 body 裡沒有 form 表單,而是在按鈕點擊時直接呼叫 ajaxFileUpload()。這正是非同步上傳與傳統表單上傳在寫法上的根本差異。

另外,JS 的載入順序不能調換:ajaxfileupload.js 依賴於 jQuery,必須排在 jQuery 之後。

還有個實務上要注意的地方:Action 中直接使用 getRealPath("/upload") 取得實體路徑,在 WAR 包未解開的部署環境下會失效;而且直接沿用使用者上傳的檔名存檔,有覆寫同名檔案與路徑攻擊的風險。正式環境請改用可設定的絕對上傳目錄,並對檔名做白名單與重新命名處理,同時限制檔案大小。範例中的 .exe 檢查只是最基本的攔阻,不能視為完整的驗證。

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