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;
	}
	
}



免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM