1. 程式人生 > >java 流讀取圖片供前臺顯示

java 流讀取圖片供前臺顯示

jsp階段

<img id="img" src="${ctx }/phone/getImg.ce?type=2&PATHID='+pathid+'"> </img>

java Controller階段

@RequestMapping("getImg")  
    @ResponseBody
	public String getImg(HttpServletRequest request, HttpServletResponse response) throws Exception {
		
		 Map<String, Object> map = getPageMapParams();	
		 List<Map<String, Object>> list_new =xcxQqandWxServices.getimgOraudiopath(map);//通過前端傳來的id獲取該圖片的路徑
		 
		 String path = (String)list_new.get(0).get("NEWFILEPATH");
		 if (path!=null) {
			 File file = new File(path);
			   // 路徑為檔案且不為空
			    if (file.isFile() && file.exists()) { 
			    	ServletOutputStream out = null;  
			        FileInputStream ips = null;  
			        try {  
			            //獲取圖片存放路徑  
			            String imgPath = path;  
			            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; 
	}