一.場景還原
用戶上傳了一張圖片,已有服務器保存路徑,現由於系統配置無法直接通過圖片URL打開預覽圖片,需實現點擊預覽將圖片顯示在瀏覽器上。

二.實現方法
html:
<a href="##" onclick="preview('${file.filePath}')" >預覽</a>
此處用預覽按鈕方法實現
Javascript:
function preview(path){ var ext=path.split('.')[1]; if(ext=="PNG"){ window.open("<%=path%>/file/showImage.do?path="+path); } }
此處因為測試判斷了PNG
Java:
/* * 在線預覽圖片 */ @RequestMapping("/showImage.do") public @ResponseBody void showImage(String path) throws IOException { getResponse().setContentType("text/html; charset=UTF-8"); getResponse().setContentType("image/jpeg"); String fullFileName = getRealPath("/upload/" + path); FileInputStream fis = new FileInputStream(fullFileName); OutputStream os = getResponse().getOutputStream(); try { int count = 0; byte[] buffer = new byte[1024 * 1024]; while ((count = fis.read(buffer)) != -1) os.write(buffer, 0, count); os.flush(); } catch (IOException e) { e.printStackTrace(); } finally { if (os != null) os.close(); if (fis != null) fis.close(); } }
三.執行結果
打開一個新的窗口,顯示圖片。
