Struts2将图片输出到页面

        在做CRUD的过程中,添加页面是个表单,表单里面有一项是上传头像文件。这样表单提交后,头像文件上传了。
但这个文件存的地址是本地硬盘的一个文件夹。在编辑页面要做这个头像的回显的话,就需要我们去本地文件读到这张图片,
然后将这张图片输出到页面。
        笔者很久都没写过怎么把图片输出到页面了,在网上看了点资料,感觉不够清晰。于是决定自己做下笔记,方便后续查阅。

一、思路

        既然是将图片回显,那么页面上图片的src属性肯定就是一个http请求,后台处理这个请求是输出一张图片到浏览器
        (1) 编辑页面的使用 <img />  标签,然后src属性值为一个http请求,这个请求带了参数
        (2) 后台通过这个请求带的参数,去数据库中查出图片的地址
        (3) 后台拿到图片地址后,用输入流和输出流的方法,把图片读进来再输出到浏览器

二、代码

        (1)页面的代码
  <td class="tdBg" width="200px">头像:</td> 
  <td>
     <!-- 显示头像  -->
     <img src="${basePath}nsfw/user_showHeadImg.action?user.id=${user.id}" width="100" height="100"/>
     <input type="file" name="headImg" accept = "image/*"/>
  </td>
        (2)后台代码
                 这里还有个图片上传的方法没删掉,方便后续查阅

package com.tax.web.user;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.List;
import java.util.UUID;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.struts2.ServletActionContext;
import org.springframework.beans.factory.annotation.Autowired;
import com.opensymphony.xwork2.ActionSupport;
import com.tax.pojo.nsfw.User;
import com.tax.service.UserService;

/**
 * UserAction
 * @author   ZENG.XIAO.YAN
 * @date 	 2017年7月11日 上午10:06:05
 * @version  v1.0
 */

public class UserAction extends ActionSupport {

	private static final long serialVersionUID = 4526496105243102063L;
	@Autowired
	private UserService userService;
	private User user;
	/** 文件上传的3个属性 */
	private File headImg;				// 这个名字和表单的name的值一样
	private String headImgFileName;
	private String headImgContentType;
	/** 存放图片的本地文件夹  */
	private static final String USER_IMAGE_DIR = "D:/upload";
	
	
	
	/** 
	 * 展示用户头像 Action方法
	 * @return 将头像输出到页面
	 * @see 访问方式:tax/nsfw/user_showHeadImg.action?user.id=xxxx
	 */
	public String showHeadImg() {
		// 这个user的id是通过前台传过来的
		if(null != user && user.getId() != null) {
			// 通过用户id去数据库查找出用户头像的地址
			String img = userService.findById(user.getId()).getHeadImg();
			if(StringUtils.isNotBlank(img)) {
				// 拼接成本地地址,如:D:/upload/user/0dc14d2b81444ce1b5600a3fe43f9f30.jpg
				// USER_IMAGE_DIR = D:/upload
				// img 如:user/0dc14d2b81444ce1b5600a3fe43f9f30.jpg
				File imgFile = new File(USER_IMAGE_DIR + "/" + img);
				// 如果图片文件存在,就输出到页面
				if(imgFile.exists()) {
					/** 获取HttpServletResponse */
					HttpServletResponse response = ServletActionContext.getResponse();
					/** 设置响应的内容类型 */
					response.setContentType("images/jpeg");
					/** 以下3行代码用于设置禁止浏览器缓存该图片 */
					response.setDateHeader("expries", -1);
					response.setHeader("Cache-Control", "no-cache");  
			        response.setHeader("Prama", "no-cache");  
			        // 以下为IO流操作
					BufferedInputStream bis = null;
					BufferedOutputStream bos = null;
					try {
						bis = new BufferedInputStream(new FileInputStream(imgFile));
						// 这个Response.getOutputStream()是用于输出到浏览器的输出流
						bos = new BufferedOutputStream(response.getOutputStream());
						byte[] buffer = new byte[1024];
						int len = 0;
						while ((len = bis.read(buffer)) != -1) {
							bos.write(buffer, 0, len);
						}
					} catch (Exception e) {
						e.printStackTrace();
					} finally {
						// 关流
						if (bis != null) {
							try {
								bis.close();
							} catch (IOException e) {
								e.printStackTrace();
							}
						}
						if (bos != null) {
							try {
								bos.close();
							} catch (IOException e) {
								e.printStackTrace();
							}
						}
					}
				}
			}
		}
		//  这里没有返回视图,直接返回NONE
		return NONE;
	}
	



	
	/**
	 * 专门用于文件上传的方法,返回文件路径
	 * @return 文件路径
	 */
	private String uploadFile() {
		try {
			if (null != headImg) {
				// 获取存放文件夹路径
				// USER_IMAGE_DIR = D:/upload
				String prePath = USER_IMAGE_DIR.concat("/user");
				if(!new File(prePath).exists()) {
					new File(prePath).mkdirs();
				}
				// 新的文件名
				String fileName = UUID.randomUUID().toString().replaceAll("-", "")
						.concat(headImgFileName.substring(headImgFileName.lastIndexOf(".")));
				// 用common-io.jar的工具copy文件
				FileUtils.copyFile(headImg, new File(prePath,fileName));
				return "user/".concat(fileName);
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}
	
	
	/** setter and getter method */

	public User getUser() {
		return user;
	}

	public void setUser(User user) {
		this.user = user;
	}

	public File getHeadImg() {
		return headImg;
	}

	public void setHeadImg(File headImg) {
		this.headImg = headImg;
	}

	public String getHeadImgFileName() {
		return headImgFileName;
	}

	public void setHeadImgFileName(String headImgFileName) {
		this.headImgFileName = headImgFileName;
	}

	public String getHeadImgContentType() {
		return headImgContentType;
	}

	public void setHeadImgContentType(String headImgContentType) {
		this.headImgContentType = headImgContentType;
	}
	
}


posted @ 2017-08-19 19:00  zeng1994  阅读(3988)  评论(2编辑  收藏  举报