工程中图片的显示"/>
javaweb工程中图片的显示
最近在项目中需要实现一个功能,门户网站上显示用户上传的头像,其实就是文件的上传与显示,这里只说头像的显示问题,通过网上查资料发现有两种实现方式,总结下来,自己备用,也分享给朋友。
第一种情况,如果照片就在工程里边,那么可以通过链接直接访问到:
如图所示,我的照片文件所在的路径为:WebContent/image/tx_deafult.png,那么在页面上的访问路径为:
这样显示正确。
第二种情况,照片文件不在工程里,而是在其他位置,例如我的文件路径是:C:\user\photo,这需要用流的方式加载,代码如下:
页面代码:
后台代码:
/*** * @description 显示照片 * @param mapping* @param form* @param request* @param response* @return* @author:wang_bjian* @date:2017年10月2日 下午1:53:11*/private ActionForward showPhoto(ActionMapping mapping,UpInfoActionForm form, HttpServletRequest request,HttpServletResponse response) { // response.setContentType("text/html; charset=UTF-8");response.setContentType("image/jpeg");//响应头控制浏览器不要缓存 response.setDateHeader("expries", -1); response.setHeader("Cache-Control", "no-cache"); response.setHeader("Pragma", "no-cache"); String rootPath = "C:/user/photo/"; // 文件存储的根目录String userid = request.getParameter("userid"); // 从前台传入的参数,useridFileInputStream fis = null;String photoPath = null; // 文件路径File photoFile = null;try {// 根据userId查询对应的文件路径,表rbac_user_photophotoPath = UpInfoBO.getPhotoPathByUserid(userid);if(null != photoPath && !"".equals(photoPath)){photoPath = rootPath + photoPath;photoFile = new File(photoPath);if(!photoFile.exists()){ // 如果头像文件不存在,说明说明头像文件已丢失,则显示默认头像String deafultPP = request.getSession().getServletContext().getRealPath("");photoPath = deafultPP + "\\image\\tx_default.png";} } else { // 如果路径为空,说明当前用户没有上传过头像,则显示默认头像String deafultPP = request.getSession().getServletContext().getRealPath("");photoPath = deafultPP + "\\image\\tx_default.png";}fis = new FileInputStream(photoPath);IOUtils.copy(fis, response.getOutputStream());} catch (Exception e) {e.printStackTrace();}finally{if(fis != null){try {fis.close();} catch (IOException e) {e.printStackTrace();}}}return null;}
其实,第二种方法是通用的,本质都是通过文件的绝对路径,取到流加载到页面。
更多推荐
javaweb工程中图片的显示
发布评论