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

Java Servlet 原生處理 JSP 表單檔案上傳(不使用框架)

     編輯:程式設計疑難解答

核心步驟

  1. JSP 表單設定 enctype="multipart/form-data" 並包含 <input type="file" name="uploadFile">。
  2. Servlet 使用 @MultipartConfig 註解(Servlet 3.0+)或手動解析 request.getInputStream()。
  3. 透過 request.getPart("uploadFile") 取得 Part 物件。
  4. 呼叫 part.getInputStream() 讀取檔案流,或 part.write(path) 直接儲存。

完整範例

1. JSP 頁面 (upload.jsp)

<form action="UploadServlet" method="post" enctype="multipart/form-data">
    <input type="file" name="uploadFile" />
    <input type="submit" value="上傳" />
</form>

2. Servlet (UploadServlet.java)

@WebServlet("/UploadServlet")
@MultipartConfig(
    fileSizeThreshold = 1024 * 1024,      // 1 MB 臨時存儲閾值
    maxFileSize = 1024 * 1024 * 10,       // 10 MB 單檔上限
    maxRequestSize = 1024 * 1024 * 50     // 50 MB 總請求上限
)
public class UploadServlet extends HttpServlet {
    private static final String UPLOAD_DIR = "uploads";

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        // 取得 Part
        Part filePart = request.getPart("uploadFile");
        if (filePart == null || filePart.getSize() == 0) {
            response.getWriter().println("未選擇檔案");
            return;
        }

        // 取得檔名(需處理瀏覽器差異)
        String fileName = getFileName(filePart);
        String applicationPath = getServletContext().getRealPath("");
        String uploadPath = applicationPath + File.separator + UPLOAD_DIR;

        File uploadDir = new File(uploadPath);
        if (!uploadDir.exists()) uploadDir.mkdirs();

        String filePath = uploadPath + File.separator + fileName;
        try (InputStream fileContent = filePart.getInputStream();
             FileOutputStream fos = new FileOutputStream(filePath)) {
            byte[] buffer = new byte[1024];
            int bytesRead;
            while ((bytesRead = fileContent.read(buffer)) != -1) {
                fos.write(buffer, 0, bytesRead);
            }
            response.getWriter().println("上傳成功:" + filePath);
        }
    }

    // 從 Content-Disposition header 解析檔名
    private String getFileName(Part part) {
        String contentDisp = part.getHeader("content-disposition");
        for (String token : contentDisp.split(";")) {
            if (token.trim().startsWith("filename")) {
                return token.substring(token.indexOf('=') + 2, token.length() - 1);
            }
        }
        return "unknown";
    }
}

關鍵注意事項

  • Servlet 3.0+ 容器(Tomcat 7+, Jetty 9+)才支援 @MultipartConfig 與 getPart()。
  • 大檔案上傳需設定 fileSizeThreshold 避免記憶體溢位,超過閾值會寫入臨時檔案。
  • 檔名需防禦路徑遍歷攻擊(過濾 .., /, \)。
  • 生產環境建議使用 Apache Commons FileUpload 或 Spring MVC 封裝,更健壯。

參考資源

詳細原始碼與解析:CSDN - Servlet 3.0 檔案上傳完整範例

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