java web项目中读取本地图片

 

java web项目中读取本地图片

标签: java web tomcat
2258人阅读  评论(2)  收藏  举报
  分类:
环境配置(3)   项目中(19)   js(10) 

在项目中,因为业务需要,用户上传的图片存放在服务器的D盘中,为了读取并显示到页面上,尝试了两种方法:

一  通过流读取

java代码:

[java]  view plain  copy
  1. @RequestMapping(value = "/seekExperts")    
  2.     @ResponseBody    
  3.     public String createFolw(HttpServletRequest request,    
  4.             HttpServletResponse response, Model model) {    
  5.         // response.setContentType("image/*");   
  6.     PageData pd = new PageData();  
  7.     pd = this.getPageData();  
  8.     //取路径  
  9.     String path = pd.getString("path");  
  10.         FileInputStream fis = null;    
  11.         OutputStream os = null;    
  12.         try {    
  13.             fis = new FileInputStream(path);    
  14.             os = response.getOutputStream();    
  15.             int count = 0;    
  16.             byte[] buffer = new byte[1024 * 8];    
  17.             while ((count = fis.read(buffer)) != -1) {    
  18.                 os.write(buffer, 0, count);    
  19.                 os.flush();    
  20.             }    
  21.         } catch (Exception e) {    
  22.             e.printStackTrace();    
  23.         }    
  24.         try {    
  25.             fis.close();    
  26.             os.close();    
  27.         } catch (IOException e) {    
  28.             e.printStackTrace();    
  29.         }    
  30.         return "ok";    
  31.     }    

前台代码:

[html]  view plain  copy
  1. <img alt="image" id="myImage" style="height:250px;width:400px;" src="defectivemanage/seekExperts.do?path=${var.PATH }"/>     


这样能够实现,但是如果访问量很大,需要多次读取流,所以不建议。


二  通过配置虚拟目录读取

打开tomcat的conf文件夹,在server.xml中的<Host></Host>标签内加入

[html]  view plain  copy
  1. <Context path="/dataResourceImages" docBase="D:\a" crossContext="true" reloadable="false" debug="0"/>  


path是虚拟路径,docBase为真实路径

jsp代码:

[html]  view plain  copy
  1. <img alt="image" id="myImage" style="height:250px;width:400px;" src="/dataResourceImages/GIF1.gif"/>  

修改后重启,就可以看到图片啦

猜你喜欢

转载自blog.csdn.net/mxd446814583/article/details/79968596
今日推荐