需求:
通過一個請求url返回一張圖片
例如

這樣有一個好處是,你發你的請求.但是你就是不知道我的實際圖片在哪兒?呵呵好耍三
代碼
View Code
/** * 通過url請求返回圖像的字節流 */ @RequestMapping("icon/{cateogry}") public void getIcon(@PathVariable("cateogry") String cateogry, HttpServletRequest request, HttpServletResponse response) throws IOException { if(StringUtils.isEmpty(cateogry)) { cateogry = ""; } String fileName = request.getSession().getServletContext().getRealPath("/") + "resource\\icons\\auth\\" + cateogry.toUpperCase().trim() + ".png"; File file = new File(fileName); //判斷文件是否存在如果不存在就返回默認圖標 if(!(file.exists() && file.canRead())) { file = new File(request.getSession().getServletContext().getRealPath("/") + "resource/icons/auth/root.png"); } FileInputStream inputStream = new FileInputStream(file); byte[] data = new byte[(int)file.length()]; int length = inputStream.read(data); inputStream.close(); response.setContentType("image/png"); OutputStream stream = response.getOutputStream(); stream.write(data); stream.flush(); stream.close(); }
