首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> Java 程式設計 >> Java 相關知識

Struts 2 檔案上傳完整指南:單檔、多檔任意數量與預設限制調整

     編輯:Java 相關知識

Struts 2 上傳機制優勢

  • 以攔截器實作 (FileUploadInterceptor),無需 ActionForm
  • 自動將上傳檔案存入暫存目錄,提供 File 物件供 Action 處理
  • 支援單檔、多檔、任意數量,配置極簡單

一、單檔上傳

Action 類別規約

屬性命名慣例 (以表單 name="upload" 為例):

用途Getter/Setter型別
暫存檔getUpload() / setUpload(File)java.io.File
原始檔名getUploadFileName() / setUploadFileName(String)String
Content-TypegetUploadContentType() / setUploadContentType(String)String

完整 Action 代碼

public class UploadAction extends ActionSupport {
    private File upload;
    private String uploadFileName;
    private String uploadContentType;
    // Getter/Setter 略...

    public String execute() throws Exception {
        try (InputStream is = new FileInputStream(upload);
             OutputStream os = new FileOutputStream("d:/upload/" + uploadFileName)) {
            byte[] buffer = new byte[8192];
            int len;
            while ((len = is.read(buffer)) > 0) os.write(buffer, 0, len);
        }
        return SUCCESS;
    }
}

JSP 表單 (需 enctype="multipart/form-data")

<s:form action="upload" namespace="/test" enctype="multipart/form-data">
  <s:file name="upload" label="選擇檔案" />
  <s:submit value="上傳" />
</s:form>

成功頁顯示屬性

<s:property value="uploadFileName" />
<s:property value="uploadContentType" />

二、任意多檔上傳

前端:JavaScript 動態產生 <input type="file">

<script>
function addFileInput() {
  var input = document.createElement("input");
  input.type = "file";
  input.name = "upload"; // 同名稱
  document.getElementById("fileList").appendChild(input);
  document.getElementById("fileList").appendChild(document.createElement("br"));
}
</script>

<input type="button" value="新增檔案" onclick="addFileInput()" />
<form action="/struts2/test/upload.action" method="post" enctype="multipart/form-data">
  <div id="fileList"><input type="file" name="upload" /><br/></div>
  <input type="submit" value="上傳" />
</form>

注意:範例使用 document.createElement("input") 相容性較佳,原文 createElement("<input ...>") 僅 IE 支援。

Action:將三個屬性改為 List

public class UploadMoreAction extends ActionSupport {
    private List<File> uploads;
    private List<String> uploadsFileName;
    private List<String> uploadsContentType;
    // Getter/Setter 略...

    public String execute() throws Exception {
        if (uploads != null) {
            for (int i = 0; i < uploads.size(); i++) {
                File src = uploads.get(i);
                String destName = uploadsFileName.get(i);
                try (InputStream is = new FileInputStream(src);
                     OutputStream os = new FileOutputStream("d:/upload/" + destName)) {
                    byte[] buffer = new byte[8192];
                    int len;
                    while ((len = is.read(buffer)) > 0) os.write(buffer, 0, len);
                }
            }
        }
        return SUCCESS;
    }
}

三、預設限制與調整

設定預設值調整方式 (struts.properties)
暫存目錄javax.servlet.context.tempdirstruts.multipart.saveDir=/custom/temp
最大檔案大小2 MB (2,097,152 bytes)struts.multipart.maxSize=2048 (單位 KB) → 2 MB

struts.properties 放在 src/ 根目錄 (同層 struts.xml)。

四、常見問題

  • 檔案名中文亂碼:確保 Tomcat server.xml Connector 設定 URIEncoding="UTF-8",且 JSP 頁面 pageEncoding="UTF-8"
  • 超過大小限制:FileUploadInterceptor 會拋出錯誤,可在 validation.xml 或 Action validate() 攔截友善提示
  • 暫存檔未清理:請求結束後攔截器會自動刪除暫存檔,若 Action 拋異常導致流程中斷,建議在 finally 或攔截器 cleanup 確保刪除

Struts 1.x vs 2.x 對比

特性Struts 1.xStruts 2
上傳元件Form Bean + MultipartRequestHandlerFileUploadInterceptor (自動裝載)
多檔處理需索引屬性 file1, file2...同名 List<File> 自動綁定
配置複雜度高極低
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved