java IO流讀取圖片供前台顯示


最近項目中需要用到IO流來讀取圖片以提供前台頁面展示,由於以前一直是用url路徑的方式進行圖片展示,一聽說要項目要用IO流讀取圖片感覺好復雜一樣,但任務下達下來了,做為程序員只有選擇去執行嘍,於是找了點資料看了會api,

嘿感覺挺簡單的,由於是第一次采用IO流的方式進行讀取圖片供頁面顯示,所以把以下代碼記錄一下

 

后台代碼:

[java]  view plain  copy
 
  1. <span style="white-space:pre">  </span>/** 
  2.      * IO流讀取圖片 by:long 
  3.      * @return 
  4.      */  
  5.     @RequestMapping(value = "/IoReadImage/{imgName}", method = RequestMethod.GET)  
  6.     public String IoReadImage(@PathVariable String imgName,HttpServletRequest request,HttpServletResponse response) throws IOException {  
  7.         ServletOutputStream out = null;  
  8.         FileInputStream ips = null;  
  9.         try {  
  10.             //獲取圖片存放路徑  
  11.             String imgPath = Constans.FOLDER_IMAGE + imgName;  
  12.             ips = new FileInputStream(new File(imgPath));  
  13.             response.setContentType("multipart/form-data");  
  14.             out = response.getOutputStream();  
  15.             //讀取文件流  
  16.             int len = 0;  
  17.             byte[] buffer = new byte[1024 * 10];  
  18.             while ((len = ips.read(buffer)) != -1){  
  19.                 out.write(buffer,0,len);  
  20.             }  
  21.             out.flush();  
  22.         }catch (Exception e){  
  23.             e.printStackTrace();  
  24.         }finally {  
  25.             out.close();  
  26.             ips.close();  
  27.         }  
  28.         return null;  
  29.     }  

前台代碼 - 方式一:

[html]  view plain  copy
 
  1. <span style="white-space:pre">  </span><div style="float: left;">  
  2.           <#--${model.userDatil.photo} 為數據庫存放的文件名稱-->  
  3.           <img src="${ctx}/userInfo/IoReadImage/${model.userDatil.photo}" id="npcImg" width="125" height="148"/>  
  4.           <input type="hidden" id="photo" name="photo"/>  
  5.         </div>  
 

js代碼 - 方式二:

 

[javascript]  view plain  copy
 
  1. var npcName = $('#npcImg').data('val');  
  2. var img = document.getElementById("npcImg");  
  3. img.src = '/userInfo/IoReadImage/'+npcName;  

jQuery代碼 - 方式三:
[javascript]  view plain  copy
 
  1. <span style="white-space:pre">  </span>$('#npcImg').attr('src','/userInfo/IoReadImage/'+npcName);  


好了就這么簡單,前台就可以顯示圖片了,總共才幾句代碼,就不額外注釋說明了

 
原文出處:
[1] 江西DJ煙仔ReMix, java IO流讀取圖片供前台顯示, http://blog.csdn.net/u014598014/article/details/70232854

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM