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

Apache Commons FileUpload 實戰:高效能檔案上傳元件完整指南

     編輯:Java 相關知識

前言:為什麼選擇 Commons FileUpload?

Java 專案需求高效能檔案上傳時,手寫 Servlet 易出錯且難維護。主流選擇為 jakarta commons-fileupload 與 smartupload。實測後者大檔上傳易出錯、中文支援不佳,故採用前者。本文提供完整封裝類別與前後端整合範例。

一、前端頁面:檔案選擇與參數傳遞

<form name="Form1" onSubmit="return check()" enctype="multipart/form-data" method="post" action="uploadResult.jsp">
  <input type="checkbox" name="checkbox" value="ch1"> 公共資料夾
  <input type="hidden" name="ch1" id="ch1" size="20">
  <input type="checkbox" name="checkbox" value="ch2"> 測試資料夾
  <input type="hidden" name="ch2" id="ch2" size="20">
  <p>選擇 Excel 檔案 <input type="file" name="File1" size="20" maxlength="20"></p>
  <p>注意:請確保為 Excel 格式,檔名勿含空格,同名自動覆蓋</p>
  <input type="submit" value="提交"> <input type="reset" value="取消">
</form>

<script>
function check() {
  if (document.Form1.checkbox[0].checked) document.Form1.ch1.value = document.Form1.checkbox[0].value;
  if (document.Form1.checkbox[1].checked) document.Form1.ch2.value = document.Form1.checkbox[1].value;
  var newAction = Form1.action + "?ch1=" + document.Form1.ch1.value + "&ch2=" + document.Form1.ch2.value;
  Form1.action = newAction;
}
</script>

二、後端處理頁面:路徑判斷與上傳呼叫

<%
String temp = "C:\\TEMP";
char[] label = new char[2];
String labelString = "";
// 初始化標記陣列
for (int i = 0; i < label.length; i++) label[i] = '0';

String des = request.getRealPath("/FinancialReports/ExcelFile");

// 依 checkbox 決定上傳子目錄
if (request.getParameterValues("ch1") != null) {
    String[] ch1 = request.getParameterValues("ch1");
    if (ch1[0].equals("ch1")) label[0] = '1';
}
if (request.getParameterValues("ch2") != null) {
    String[] ch2 = request.getParameterValues("ch2");
    if (ch2[0].equals("ch2")) label[1] = '1';
}
for (int i = 0; i < label.length; i++) labelString += label[i];
des = des + "\\" + labelString;

Fileupload fileUpload = new Fileupload(temp, des, request);
boolean uploadResult = fileUpload.Upload(true);
%>

三、Fileupload 封裝類別完整原始碼

package net.hyweb;

import java.io.File;
import java.util.*;
import org.apache.commons.fileupload.*;
import javax.servlet.http.HttpServletRequest;

public class Fileupload {
    private String tempPath = "C:\\TEMP";
    private String destinationPath;
    private HttpServletRequest fileuploadRequest;
    private int sizeThreshold = 4096;        // 記憶體緩衝閾值 (bytes)
    private long sizeMax = 10485760;         // 最大上傳 10MB

    public Fileupload() {}
    public Fileupload(String tempPath, String destinationPath) {
        this.tempPath = tempPath;
        this.destinationPath = destinationPath;
    }
    public Fileupload(String tempPath, String destinationPath, HttpServletRequest request) {
        this(tempPath, destinationPath);
        this.fileuploadRequest = request;
    }

    public boolean Upload() {
        // 確保暫存與目標目錄存在
        ensureDirectory(tempPath);
        ensureDirectory(destinationPath);

        DiskFileUpload fu = new DiskFileUpload();
        fu.setSizeThreshold(sizeThreshold);
        fu.setSizeMax(sizeMax);
        fu.setRepositoryPath(tempPath);

        List fileItems;
        try {
            fileItems = fu.parseRequest(fileuploadRequest);
        } catch (FileUploadException e) {
            e.printStackTrace();
            return false;
        }

        Iterator iter = fileItems.iterator();
        while (iter.hasNext()) {
            FileItem item = (FileItem) iter.next();
            if (!item.isFormField()) { // 檔案欄位
                String fieldName = item.getFieldName();
                String name = item.getName();
                if (name == null || name.equals("") || item.getSize() == 0) continue;

                String fileName = getFileName(name);
                try {
                    item.write(new File(destinationPath + fileName));
                } catch (Exception e) {
                    e.printStackTrace();
                    return false;
                }
            } else { // 一般表單欄位
                // 可依需求處理其他參數
            }
        }
        return true;
    }

    private void ensureDirectory(String path) {
        File dir = new File(path);
        if (!dir.isDirectory()) {
            try { dir.mkdirs(); }
            catch (SecurityException e) { System.out.println("無法建立目錄: " + path); }
        }
    }

    public String getFileName(String filepath) {
        String filename = "*.*";
        if (filepath != null && filepath.length() > 0) {
            filepath = filepath.replace('\\', '/');
            int idx = filepath.lastIndexOf('/');
            if (idx >= 0) filename = filepath.substring(idx + 1);
        }
        return filename;
    }
    // 省略 getter/setter
}

四、關鍵設定說明

參數預設值說明
sizeThreshold4096 bytes超過此大小改寫入暫存檔,避免記憶體溢位
sizeMax10 MB限制單次上傳總大小,防止 DoS
repositoryPathtempPath暫存檔存放目錄

五、部署注意事項

  1. 需引入 commons-fileupload.jar 與 commons-io.jar
  2. 表單必須設定 enctype="multipart/form-data"
  3. 生產環境建議調大 sizeMax 並加入檔案類型驗證
  4. 暫存目錄需具備寫入權限

原始碼開源,引用請註明出處:Huang ye (www.hyweb.net)

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved