从数据库中读取图片路径,然后从服务器本地读取并在页面显示出来,由于本地服务器权限问题一直不能直接读取,几经周折使用layer得以实现,特记录下来以供后续参考:
前端代码:
<td id="imgs"> <c:if test="${rpReportBl.img != null}"> <a href='javascript:picLook("${rpReportBl.img}");' >图片预览</a> </c:if> </td>
JS:
<script type="text/javascript"> function picLook(fileUrls){ if(fileUrls != ''){ var pic = fileUrls.split(';'); var data = []; for(var i=0;i<pic.length;i++){ if(pic[i] != '' ){ var picData = { src:"${ctx}/redpacket/rpReportBl/getPic?fileName="+pic[i],//原图地址,此处为路径,返回二进制数据 alt:pic[i] //图片名字 }; data.push(picData);//将多个图片属性存入data数组 } } layer.photos({ closeBtn:true,//右上关闭 photos: { data : data //将数组放入 } }); }else{ alert('没有图片'); } } </script>
后台代码:
/** * 返回图片流 * @param fileName * @param request * @param response * @return */ @RequestMapping(value = "getPic") public String IoReadImage( String fileName,HttpServletRequest request,HttpServletResponse response) { ServletOutputStream out = null; FileInputStream ips = null; try { //获取图片存放路径 String imgPath = Global.getConfig("imgsurl")+ File.separator+fileName; 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){ logger.error("",e); }finally { try { out.close(); } catch (IOException e) { logger.error("",e); } try { ips.close(); } catch (IOException e) { logger.error("",e); } } return null; }如有不足之处,请指出共勉!