圖片文件存儲在服務器磁盤目錄,SQL Server 2000 表中僅存儲相對/絕對路徑字符串。Java 應用需讀取路徑,加載圖片流輸出至前端或保存副本。
SELECT pic_path FROM table WHERE id = ? 獲取路徑字符串。java.io.FileInputStream 讀取磁盤文件流。HttpServletResponse.getOutputStream() 或寫入新文件。
@WebServlet("/showPic")
public class ShowPicServlet extends HttpServlet {
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
String picPath = req.getParameter("path"); // 從請求獲取路徑參數
// 安全校驗:防止目錄遍歷攻擊
if (picPath == null || picPath.contains("..")) {
resp.sendError(HttpServletResponse.SC_BAD_REQUEST);
return;
}
File imgFile = new File(BASE_UPLOAD_DIR, picPath); // 基礎目錄 + 相對路徑
if (!imgFile.exists() || !imgFile.isFile()) {
resp.sendError(HttpServletResponse.SC_NOT_FOUND);
return;
}
resp.setContentType(getContentType(picPath)); // 根據擴展名設置 MIME
try (InputStream is = new FileInputStream(imgFile);
OutputStream os = resp.getOutputStream()) {
byte[] buffer = new byte[4096];
int len;
while ((len = is.read(buffer)) != -1) os.write(buffer, 0, len);
}
}
private String getContentType(String fileName) {
if (fileName.endsWith(".png")) return "image/png";
if (fileName.endsWith(".jpg") || fileName.endsWith(".jpeg")) return "image/jpeg";
if (fileName.endsWith(".gif")) return "image/gif";
return "application/octet-stream";
}
}
../../etc/passwd 類攻擊。Files.copy(Path, OutputStream) (NIO.2) 或 sendfile 系統調用(需容器支持)提升性能。