圖片存放在服務器硬盤絕對路徑,數據庫僅存路徑。JSP 中直接用 <img src="絕對路徑"> 無法訪問,因為瀏覽器無法訪問服務器本地文件系統。
建立一個 Servlet(如 ImageServlet),接收圖片相對路徑參數,讀取文件並以二進制流輸出到響應。
@WebServlet("/image")
public class ImageServlet extends HttpServlet {
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
String relativePath = req.getParameter("path"); // 如 "201701/photo.jpg"
if (relativePath == null) { resp.sendError(404); return; }
// 服務器存儲根目錄(可配置在 web.xml 或屬性文件)
String baseDir = getServletContext().getRealPath("/uploads");
File file = new File(baseDir, relativePath);
if (!file.exists() || !file.isFile()) { resp.sendError(404); return; }
// 設置正確的 Content-Type(可根據擴展名動態判斷)
String mime = getServletContext().getMimeType(file.getName());
resp.setContentType(mime != null ? mime : "application/octet-stream");
resp.setContentLengthLong(file.length());
try (FileInputStream fis = new FileInputStream(file);
OutputStream os = resp.getOutputStream()) {
byte[] buffer = new byte[8192];
int len;
while ((len = fis.read(buffer)) != -1) {
os.write(buffer, 0, len);
}
}
}
}
<img src="image?path=201701/photo.jpg" alt="圖片">
/image 成為虛擬訪問入口。..)。BufferedInputStream 或 NIO 零拷貝;靜態資源可直接配置 Web 容器映射目錄(Tomcat docBase、Nginx alias)。Cache-Control、ETag 減少重複傳輸。通過 Servlet 讀取服務器本地文件並輸出二進制流,配合正確的 MIME 類型,即可在 JSP/HTML 中像訪問普通圖片 URL 一樣顯示服務器絕對路徑下的圖片。