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

Servlet 文件上傳至 WebRoot/upload 目錄:getServletContext().getRealPath() 獲取絕對路徑

     編輯:程式設計綜合問答

問題

Servlet 使用 Apache Commons FileUpload 上傳文件,當前代碼硬編碼保存路徑 C:\\upload_test,需改為動態獲取 Web 應用根目錄下的 upload 文件夾。

核心修正

// 原代碼
File saved = new File("C:\\upload_test", fileName);

// 修正後
String filePath = getServletContext().getRealPath("/") + "upload" + File.separator;
File uploadDir = new File(filePath);
if (!uploadDir.exists()) uploadDir.mkdirs();
File saved = new File(uploadDir, fileName);

關鍵點解析

  • getServletContext().getRealPath("/") 返回 Web 應用在服務器文件系統上的絕對路徑(如 /var/lib/tomcat/webapps/myapp/ 或 C:\Tomcat\webapps\myapp\)。
  • 拼接 upload 目錄,使用 File.separator 保證跨平台兼容。
  • 上傳前檢查目錄是否存在,不存在則 mkdirs() 創建。
  • 生產環境建議將上傳目錄配置在 web.xml context-param 或外部配置文件,避免硬編碼。

完整 doPost 片段

protected void doPost(HttpServletRequest request, HttpServletResponse response) 
        throws ServletException, IOException {
    ServletFileUpload upload = new ServletFileUpload(new DiskFileItemFactory());
    List items = upload.parseRequest(request);
    String basePath = getServletContext().getRealPath("/") + "upload" + File.separator;
    File baseDir = new File(basePath);
    if (!baseDir.exists()) baseDir.mkdirs();

    for (FileItem item : items) {
        if (!item.isFormField()) {
            String fileName = new File(item.getName()).getName(); // 防止路徑遍歷
            File saved = new File(baseDir, fileName);
            try (InputStream in = item.getInputStream();
                 FileOutputStream out = new FileOutputStream(saved)) {
                byte[] buffer = new byte[1024];
                int len;
                while ((len = in.read(buffer)) > 0) out.write(buffer, 0, len);
            }
            response.getWriter().println("已保存:" + saved.getAbsolutePath());
        }
    }
}

安全提示

  • 校驗文件類型、大小、副檔名,防止惡意腳本上傳。
  • 文件名隨機化(UUID + 原副檔名),避免覆蓋與路徑遍歷攻擊。
  • 上傳目錄設置為不可執行(Nginx/Apache 配置 location /upload { deny all; } 或 IIS 移除執行權限)。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved