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

Struts 2 文件上傳實戰:攔截器配置、Action 處理與大小類型限制

     編輯:Java 綜合教學

核心依賴

Struts 2 內建 fileUpload 攔截器 (基於 Apache Commons FileUpload),需確保類路徑包含:

  • commons-fileupload-1.3.x.jar
  • commons-io-2.x.jar

前端表單 (關鍵屬性)



    
    

必須:enctype="multipart/form-data",<s:file> 的 name 屬性 (如 myFile) 決定 Action 中屬性名。

Action 類屬性約定 (自動注入)


public class FileUploadAction extends ActionSupport {
    private File myFile;                // 上傳文件對象
    private String myFileFileName;      // 原始文件名
    private String myFileContentType;   // MIME 類型

    // Getter/Setter 省略

    public String execute() {
        String saveDir = ServletActionContext.getServletContext().getRealPath("/upload");
        File dest = new File(saveDir, myFileFileName);
        try {
            FileUtils.copyFile(myFile, dest); // commons-io
            addActionMessage("上傳成功: " + myFileFileName);
        } catch (IOException e) {
            addActionError("上傳失敗: " + e.getMessage());
            return ERROR;
        }
        return SUCCESS;
    }
}

命名規則:屬性名、屬性名FileName、屬性名ContentType。

struts.xml 配置 (攔截器參數)



    
        10485760 
        
            image/jpeg,image/png,application/pdf
        
    
    /upload_result.jsp
    /upload_form.jsp 

參數說明:

  • maximumSize:字節單位,超過返回 input,字段錯誤鍵 struts.messages.error.file.too.large。
  • allowedTypes:逗號分隔 MIME 類型,不匹配返回 input,錯誤鍵 struts.messages.error.content.type.not.allowed。
  • allowedExtensions:可選,按擴展名過濾 (如 jpg,png,pdf)。

國際化提示配置 (struts-messages.properties)


struts.messages.error.file.too.large=文件大小不能超過 {0} 字節
struts.messages.error.content.type.not.allowed=不支持的文件類型: {0}

進階:多文件上傳


// JSP

 // 同名

// Action
private List files;
private List filesFileName;
private List filesContentType;
// 遍歷列表處理
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved