萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> JSP 程式設計

JSP 檔案上傳 JavaBean 完整實作 (簡易版)

設計思路

檔案上傳核心在於解析 multipart/form-data 請求體。本 Bean 手工解析請求輸入流,提取檔案內容並寫入磁碟。適合學習原理,生產環境建議使用 Apache Commons FileUpload 或 Servlet 3.0 @MultipartConfig。

完整 Bean 代碼

package yuanyifileup;

import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.jsp.PageContext;

public class yuanyifileup {
    private ServletRequest request;
    private ServletResponse response;
    private ServletConfig config;
    private ServletInputStream DATA;
    private int FormSize;
    private File f1;
    private FileOutputStream os;
    private DataInputStream is;
    private String filename;
    private byte[] b;
    private byte t;
    private boolean flag = false;

    public yuanyifileup() {}

    // 從 Servlet 初始化
    public void initialize(ServletConfig config, HttpServletRequest request, HttpServletResponse response) throws IOException {
        this.request = request; this.response = response; this.config = config;
        DATA = request.getInputStream();
        FormSize = request.getContentLength();
    }

    // 從 JSP PageContext 初始化
    public void initialize(PageContext pageContext) throws IOException {
        request = pageContext.getRequest();
        response = pageContext.getResponse();
        config = pageContext.getServletConfig();
        DATA = request.getInputStream();
        FormSize = request.getContentLength();
    }

    // 設定儲存路徑與檔名
    public boolean setFilename(String s) {
        try {
            f1 = new File(s);
            os = new FileOutputStream(f1);
            return true;
        } catch (IOException e) { return false; }
    }

    // 讀取整個請求體到位元組陣列
    public void getByte() {
        int i = 0;
        try {
            is = new DataInputStream(DATA);
            b = new byte[FormSize];
            while (true) {
                try {
                    t = is.readByte();
                    b[i++] = t;
                } catch (EOFException e) { break; }
            }
            is.close();
        } catch (IOException e) {}
    }

    // 解析 multipart 並儲存檔案
    public boolean save() {
        int i = 0, start1 = 0, start2 = 0;
        String temp = "";
        if (!flag) { getByte(); flag = true; }

        try {
            temp = new String(b, "ISO8859_1");
        } catch (UnsupportedEncodingException e) { return false; }

        // 尋找檔案部分起始位置
        start1 = temp.indexOf("image/");
        if (start1 == -1) return false; // 非圖片或格式異常
        temp = temp.substring(start1);
        start1 = temp.indexOf("\r\n\r\n");
        if (start1 == -1) return false;
        temp = temp.substring(start1 + 4); // 跳過雙 CRLF

        // 尋找結束邊界
        start2 = temp.indexOf("\r\n--");
        if (start2 != -1) temp = temp.substring(0, start2);

        try {
            byte[] img = temp.getBytes("ISO8859_1");
            for (i = 0; i < img.length; i++) os.write(img[i]);
            os.close();
            return true;
        } catch (IOException e) { return false; }
    }
}

JSP 頁面調用範例

<%@ page import="yuanyifileup.yuanyifileup" %>
<%
    yuanyifileup up = new yuanyifileup();
    up.initialize(pageContext);
    // 設定儲存完整路徑 (實際專案請驗證路徑安全性)
    up.setFilename("D:/uploads/" + System.currentTimeMillis() + ".jpg");
    boolean ok = up.save();
    out.println(ok ? "上傳成功" : "上傳失敗");
%>

前端表單 (必須設定 enctype)

<form action="upload.jsp" method="post" enctype="multipart/form-data">
    <input type="file" name="myfile">
    <input type="submit" value="上傳">
</form>

代碼局限與改進方向

現代標準做法 (Servlet 3.0+)

@WebServlet("/upload")
@MultipartConfig(maxFileSize = 1024*1024*10) // 10MB
public class UploadServlet extends HttpServlet {
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Part filePart = req.getPart("myfile");
        String fileName = Paths.get(filePart.getSubmittedFileName()).getFileName().toString();
        filePart.write("/uploads/" + fileName); // 容器自動處理臨時檔、編碼、大檔
        resp.getWriter().print("上傳成功");
    }
}
copyright © 萬盛學電腦網 all rights reserved
限制說明改進
僅支援單檔上傳未解析多部分邊界解析 boundary,循環處理每個 part
硬編碼尋找 "image/"只能上傳圖片,且依賴 Content-Type 順序正規解析 Content-Disposition header 取得檔名
一次性讀取整個請求體到記憶體大檔案會 OOM邊讀邊寫,或使用臨時檔案緩衝
無檔案大小、類型驗證安全風險前後端雙重驗證
字元編碼固定 ISO8859_1中文檔名亂碼依 RFC 5987 / Servlet 規範處理編碼