最近項目中需要用到IO流來讀取圖片以提供前台頁面展示,由於以前一直是用url路徑的方式進行圖片展示,一聽說要項目要用IO流讀取圖片感覺好復雜一樣,但任務下達下來了,做為程序員只有選擇去執行嘍,於是找了點資料看了會api,
嘿感覺挺簡單的,由於是第一次采用IO流的方式進行讀取圖片供頁面顯示,所以把以下代碼記錄一下
后台代碼:
- <span style="white-space:pre"> </span>
-
-
-
- @RequestMapping(value = "/IoReadImage/{imgName}", method = RequestMethod.GET)
- public String IoReadImage(@PathVariable String imgName,HttpServletRequest request,HttpServletResponse response) throws IOException {
- ServletOutputStream out = null;
- FileInputStream ips = null;
- try {
-
- String imgPath = Constans.FOLDER_IMAGE + imgName;
- ips = new FileInputStream(new File(imgPath));
- response.setContentType("multipart/form-data");
- out = response.getOutputStream();
-
- int len = 0;
- byte[] buffer = new byte[1024 * 10];
- while ((len = ips.read(buffer)) != -1){
- out.write(buffer,0,len);
- }
- out.flush();
- }catch (Exception e){
- e.printStackTrace();
- }finally {
- out.close();
- ips.close();
- }
- return null;
- }
前台代碼 - 方式一:
- <span style="white-space:pre"> </span><div style="float: left;">
- <#--${model.userDatil.photo} 為數據庫存放的文件名稱-->
- <img src="${ctx}/userInfo/IoReadImage/${model.userDatil.photo}" id="npcImg" width="125" height="148"/>
- <input type="hidden" id="photo" name="photo"/>
- </div>
js代碼 - 方式二:
- var npcName = $('#npcImg').data('val');
- var img = document.getElementById("npcImg");
- img.src = '/userInfo/IoReadImage/'+npcName;
jQuery代碼 - 方式三:
- <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