图片实现预览

java IO流读取图片供前台显示
        </h1>
        <div class="clear"></div>
        <div class="postBody">

最近项目中需要用到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
原文地址:https://www.cnblogs.com/fcj-blog/p/13959671.html