前台jsp頁面添加一個img標簽,然后src指向一個控制器的方法來獲取圖片
<img id="mutationImage" style="height: 100px; width: 100px;" src="${pageContext.request.contextPath}/b065/getImg?imgPath=${plugin.equipment_img1}" />
后台代碼
@RequestMapping("getImg")
public void getImg(String imgPath,HttpServletRequest request,HttpServletResponse response){
try {
log.info("54 [B065] imgPath: "+imgPath);
log.info("54 [B065] img read start ");
File f=new File(imgPath);
if (f.exists()) {
InputStream is = new FileInputStream(f);
int i = is.available(); // 得到文件大小
byte[] buffer = new byte[i];
s.read(buffer); // 讀數據
is.close();
response.setContentType("image/*"); // 設置返回的文件類型
OutputStream toClient = response.getOutputStream(); // 得到向客戶端輸出二進制數據的對象
toClient.write(buffer); // 輸出數據
toClient.close();
log.info("54 [B065] img read end ");
}
} catch (Exception e) {
e.printStackTrace();
}
}
這樣寫基本實現了我們想要的功能,但是問題來了,當我們通過修改功能,修改了后台服務器上的圖片的時候,我們前台的jsp圖片並沒有刷新,
而還是原來的圖片,這是什么問題呢,因為這是瀏覽器緩存干的,那怎么解決呢?
只需要一個js函數就可以了。Math.random
<img id="mutationImage" style="height: 250px; width: 300px;"src="/b065/getImg?imgPath=${plbean.equipment_img3}&check="+Math.random() />
原來的src是固定不變的瀏覽器加載還是以前的圖片,也不會執行controller方法去加載圖片,我們加一個隨機數后,這樣每次的url都不一樣,
那么原來圖片不刷新的問題就解決了