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

Struts2 文件上傳下載完整實現:Action、攔截器配置、中文文件名編碼處理、流式傳輸代碼全解析

     編輯:Java 相關知識

Struts2 文件上傳下載是 Web 開發高頻需求。本文提供完整項目結構、上傳/下載 Action 代碼、struts.xml 配置、中文文件名編碼解決方案、大文件流式傳輸優化等生產級實現方案。

項目結構

src/
  com/
    UploadAction.java
    DownLoadAction.java
web/
  upload.jsp
  download.jsp
struts.xml

上傳 Action 核心代碼

public class UploadAction extends ActionSupport {
    private File[] uploadFile;           // 上傳文件
    private String[] uploadFileFileName; // 原始文件名
    private String[] uploadFileContentType; // MIME 類型
    private String savePath = "file/";   // 保存相對路徑

    // Getter/Setter 省略

    public String execute() {
        for (int i = 0; i < uploadFile.length; i++) {
            File dest = new File(ServletActionContext.getServletContext().getRealPath(savePath), uploadFileFileName[i]);
            copy(uploadFile[i], dest);
        }
        return SUCCESS;
    }

    private static void copy(File src, File dst) {
        try (InputStream in = new BufferedInputStream(new FileInputStream(src));
             OutputStream out = new BufferedOutputStream(new FileOutputStream(dst))) {
            byte[] buffer = new byte[16 * 1024];
            int len;
            while ((len = in.read(buffer)) > 0) out.write(buffer, 0, len);
        } catch (IOException e) { throw new RuntimeException(e); }
    }
}

下載 Action 核心代碼(支持中文文件名)

public class DownLoadAction extends ActionSupport {
    private String fileName;  // 請求參數文件名
    private String savePath = "file/";

    public String execute() {
        this.fileName = ServletActionContext.getRequest().getParameter("fileName");
        return SUCCESS;
    }

    // 提供 InputStream 給 stream Result 類型使用
    public InputStream getDownloadFile() throws UnsupportedEncodingException {
        String decoded = new String(fileName.getBytes("ISO8859-1"), "UTF-8");
        return ServletActionContext.getServletContext().getResourceAsStream(savePath + decoded);
    }

    // Content-Disposition 編碼處理
    public String getDownloadChineseFileName() {
        try {
            return new String(fileName.getBytes(), "ISO8859-1");
        } catch (UnsupportedEncodingException e) { return fileName; }
    }
}

struts.xml 關鍵配置

<package name="file" namespace="/file" extends="struts-default">
  <action name="upload" class="com.UploadAction">
    <interceptor-ref name="defaultStack">
      <param name="fileUpload.maximumSize">10485760</param> <!-- 10MB -->
    </interceptor-ref>
    <result name="success">/upload_success.jsp</result>
  </action>

  <action name="download" class="com.DownLoadAction">
    <result name="success" type="stream">
      <param name="contentType">application/octet-stream</param>
      <param name="inputName">downloadFile</param>          <!-- 對應 getDownloadFile() -->
      <param name="contentDisposition">attachment;filename="${downloadChineseFileName}"</param>
      <param name="bufferSize">4096</param>
    </result>
  </action>
</package>

關鍵點總結

  • 上傳依賴 fileUpload 攔截器,自動注入 File[]/String[] 屬性
  • 下載使用 type="stream" Result,配合 getXxx() 方法輸出流
  • 中文文件名雙重編碼:請求參數 ISO8859-1 → UTF-8,響應頭 UTF-8 → ISO8859-1
  • 大文件必須使用緩衝流(BufferedInputStream/OutputStream)避免 OOM
  • 生產環境建議:文件類型白名單、大小限制、病毒掃描、分佈式存儲(MinIO/S3)
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved