javaweb工程中图片的显示

本文介绍了在JavaWeb项目中如何实现用户头像的显示。包括两种情况:当图片位于工程内部时,可以直接通过链接访问;当图片存放在外部路径,如C:userphoto时,需要使用流方式加载。提供了前端页面和后台的代码示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

        最近在项目中需要实现一个功能,门户网站上显示用户上传的头像,其实就是文件的上传与显示,这里只说头像的显示问题,通过网上查资料发现有两种实现方式,总结下来,自己备用,也分享给朋友。

     第一种情况,如果照片就在工程里边,那么可以通过链接直接访问到:

     

     如图所示,我的照片文件所在的路径为: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");  // 从前台传入的参数,userid
		FileInputStream fis = null;
		String photoPath = null; // 文件路径
		File photoFile = null;
		
		try {
			// 根据userId查询对应的文件路径,表rbac_user_photo
			photoPath = 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;
	}


     其实,第二种方法是通用的,本质都是通过文件的绝对路径,取到流加载到页面。

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值