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

Struts2 文件上傳完整實戰:從 JAR 依賴到 Action 處理流程

     編輯:Java 綜合教學

依賴 JAR 包

  • struts2-core
  • commons-fileupload
  • commons-io
Struts2上傳依賴包

web.xml 配置核心 Filter

<filter>
    <filter-name>struts2</filter-name>
    <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
</filter>
<filter-mapping>
    <filter-name>struts2</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>

struts.xml 映射 Action

<package name="default" extends="struts-default">
    <action name="myupload" class="com.xmgc.sc.action.MyUpLoadAction">
        <result name="success">/uploadResult.jsp</result>
    </action>
</package>

Action 類:自動注入文件元數據

public class MyUpLoadAction {
    private String title;              // 普通字段
    private File upload;               // 上傳文件(屬性名 = )
    private String uploadContentType;  // 文件 MIME 類型(屬性名 = upload + ContentType)
    private String uploadFileName;     // 原始文件名(屬性名 = upload + FileName)

    // Getter/Setter 省略...

    public String execute() throws IOException {
        System.out.println("Title: " + title);
        System.out.println("ContentType: " + uploadContentType);
        System.out.println("FileName: " + uploadFileName);

        // 獲取 Web 根路徑下 myupload 目錄
        String realPath = ServletActionContext.getServletContext().getRealPath("/");
        String destPath = realPath + "myupload/" + uploadFileName;

        // 流式複製
        try (FileInputStream fis = new FileInputStream(upload);
             FileOutputStream fos = new FileOutputStream(destPath)) {
            byte[] buffer = new byte[1024];
            int len;
            while ((len = fis.read(buffer)) > 0) {
                fos.write(buffer, 0, len);
            }
        }
        return "success";
    }
}

JSP 頁面:關鍵 enctype

<form action="myupload.action" method="post" enctype="multipart/form-data">
    文件名:<input type="text" name="title"/><br/>
    上傳:<input type="file" name="upload"/><br/>
    <input type="submit" value="上傳"/>
</form>

核心機制總結

  1. enctype="multipart/form-data" 讓瀏覽器以多部分形式發送二進制數據。
  2. Struts2 FileUploadInterceptor 攔截請求,將文件保存到臨時目錄,自動注入 File、ContentType、FileName 三個屬性。
  3. Action 中通過流將臨時文件複製到業務目錄,完成持久化。
  4. 最大上傳大小可在 struts.xml 配置 <constant name="struts.multipart.maxSize" value="10485760"/>(10MB)。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved