JSP顯示伺服器路徑下的圖片
阿新 • • 發佈:2019-02-08
在JSP頁面中顯示圖片,需要用到<img src="" />標籤,src可以指向圖片的絕對路徑和相對路徑,對於靜態圖片的顯示一般用:src="/source/image/xxx.png"。但通常情況下,我們需要顯示的圖片並不在專案路徑下,而是存放在伺服器的某個路徑下,需要顯示動態的圖片檔案。因此我們需要通過流的方式進行圖片顯示。
最簡單的方式:1.JSP採用<img src="">標籤 2.後臺獲取圖片路徑並以流的方式輸出
1.JSP
<div style="float: left;margin-left: 50px"> <img src= "${rootPath}/invenTask/showImage?filename=ios.png" /> </div> <div style="float: right;margin-right: 50px"> <img src= "${rootPath}/invenTask/showImage?filename=android.png" /> </div>
2.showImageByType後臺類
/** * 顯示二維碼圖片 * @param model * @param request * @return * @throws Exception */ @RequestMapping("showImage") public void showImageByType(String filename,HttpServletRequest request,HttpServletResponse response) throws Exception{ InputStream inputStream = null; OutputStream writer = null; try { inputStream = new FileInputStream(new File("D:\png\"+filename)); writer = response.getOutputStream(); byte[] buf = new byte[1024]; int len = 0; while ((len = inputStream.read(buf)) != -1) { writer.write(buf, 0, len); //寫 } inputStream.close(); } catch (Exception e) { logger.error(e.getMessage(),e); } finally{ try { if(inputStream != null){ inputStream.close(); } if(writer != null){ writer.close(); } } catch (IOException e) { logger.error(e.getMessage(),e); } } }