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

Struts2 文件上傳兩種實現方式完整對比

     編輯:Java 程式設計入門

方式一:Action 屬性自動注入

Struts2 拦截器自動將上傳文件封裝為 File 屬性,並注入 fileName、contentType。

Action 代碼

public class UploadAction extends ActionSupport {
    private File image;
    private String imageFileName;
    private String imageContentType;

    public String execute() {
        String realPath = ServletActionContext.getServletContext().getRealPath("/images");
        if (image != null) {
            File dest = new File(new File(realPath), imageFileName);
            FileUtils.copyFile(image, dest); // commons-io
            ActionContext.getContext().put("message", "上傳成功");
        }
        return SUCCESS;
    }
    // getter/setter 省略
}

方式二:手動流拷貝 + 依賴注入保存路徑

Action 代碼

public class UploadAction2 extends ActionSupport {
    private File image;
    private String imageFileName;
    private String imageContentType;
    private String savePath; // struts.xml 注入

    @Override
    public String execute() {
        try (FileOutputStream fos = new FileOutputStream(getSavePath() + "/" + imageFileName);
             FileInputStream fis = new FileInputStream(image)) {
            byte[] buffer = new byte[1024];
            int len;
            while ((len = fis.read(buffer)) > 0) fos.write(buffer, 0, len);
        } catch (Exception e) { e.printStackTrace(); return ERROR; }
        return SUCCESS;
    }
    public String getSavePath() throws Exception {
        return ServletActionContext.getServletContext().getRealPath(savePath);
    }
    // getter/setter 省略
}

struts.xml 關鍵配置

<constant name="struts.multipart.maxSize" value="10701096"/> <!-- 10MB -->
<constant name="struts.multipart.saveDir" value="d:/tmp"/>

<package name="upload2" extends="struts-default">
    <action name="upload2" class="com.ljq.action.UploadAction2">
        <param name="savePath">/images</param>
        <interceptor-ref name="fileUpload">
            <param name="allowedTypes">image/bmp,image/png,image/gif,image/jpeg</param>
            <param name="maximumSize">1025956</param>
        </interceptor-ref>
        <interceptor-ref name="defaultStack"/>
        <result name="success">/WEB-INF/page/message.jsp</result>
        <result name="input">/upload/upload.jsp</result>
    </action>
</package>

前端表單

<form action="${pageContext.request.contextPath}/upload2/upload2.do" 
      enctype="multipart/form-data" method="post">
    文件: <input type="file" name="image">
    <input type="submit" value="上傳">
</form>

兩種方式對比

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved
維度方式一方式二
代碼簡潔度高(依賴 commons-io)低(手動流控制)
靈活性固定保存邏輯可控制緩衝區、斷點續傳擴展
異常處理框架統一需自行捕獲
推薦場景常規業務上傳特殊存儲邏輯、大文件分片