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

Java SmartUpload 元件實作檔案上傳完整指南

     編輯:關於JSP

檔案上傳兩種實作方式比較

不使用元件:Apache Commons FileUpload

手動解析 multipart/form-data 請求,程式碼複雜但可控性高。核心類別:DiskFileItemFactory、ServletFileUpload、FileItem。

// 關鍵步驟
DiskFileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
upload.setFileSizeMax(maxSize);
List<FileItem> items = upload.parseRequest(request);
// 區分一般參數與檔案欄位
// 手動處理輸入/輸出流儲存檔案

使用 SmartUpload 元件(推薦簡化開發)

SmartUpload 為 smartupload.jar,放入 classpath 或 TOMCAT_HOME/lib 即可使用。特點:

  • API 簡單直觀
  • 內建檔案類型限制
  • 輕鬆取得檔名、副檔名、大小

SmartUpload 實作範例

單一檔案上傳

<!-- HTML 表單 -->
<form action="smartupload_demo01.jsp" method="post" enctype="multipart/form-data">
  圖片<input type="file" name="pic">
  <input type="submit" value="上傳">
</form>

// JSP 處理
<%@ page import="com.jspsmart.upload.*" %>
<%
  SmartUpload smart = new SmartUpload();
  smart.initialize(pageContext);
  smart.upload();
  smart.save("upload"); // 儲存至 upload 目錄
  out.print("上傳成功");
%>

批次多檔上傳

<%@ page import="com.jspsmart.upload.*" %>
<%@ page import="com.zhou.study.IPTimeStamp" %>
<%
  SmartUpload smart = new SmartUpload();
  smart.initialize(pageContext);
  smart.upload();
  IPTimeStamp its = new IPTimeStamp("192.168.1.1");
  for (int x = 0; x < smart.getFiles().getCount(); x++) {
    String ext = smart.getFiles().getFile(x).getFileExt();
    String fileName = its.getIPTimeRand() + "." + ext;
    smart.getFiles().getFile(x).saveAs(
      getServletContext().getRealPath("/") + "upload" + File.separator + fileName);
  }
  out.print("上傳成功");
%>

檔案重命名工具類 IPTimeStamp

package com.zhou.study;
public class IPTimeStamp {
  private SimpleDateFormat sdf;
  private String ip;
  public String getIPTimeRand() {
    StringBuffer buf = new StringBuffer();
    if (ip != null) {
      String[] s = ip.split("\\.");
      for (String part : s) buf.append(addZero(part, 3));
    }
    buf.append(getTimeStamp());
    Random r = new Random();
    for (int i = 0; i < 3; i++) buf.append(r.nextInt(10));
    return buf.toString();
  }
  // 格式:IP段(3碼) + 時間戳(yyyyMMddHHmmssSSS) + 3位隨機數
  // 例:19216800100120240109143045123456
}

注意事項

  1. Tomcat 專案目錄下必須建立 upload 資料夾
  2. 預設上傳檔名為原始檔名,建議重命名避免衝突
  3. 大檔上傳需調整 maxSize 參數
  4. 生產環境應加入檔案類型驗證、病毒掃描、權限控管
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved