在做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>
6
1
<td class="tdBg" width="200px">頭像:</td>
2
<td>
3
<!-- 顯示頭像 -->
4
<img src="${basePath}nsfw/user_showHeadImg.action?user.id=${user.id}" width="100" height="100"/>
5
<input type="file" name="headImg" accept = "image/*"/>
6
</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;
}
}
x
1
package com.tax.web.user;
2
3
import java.io.BufferedInputStream;
4
import java.io.BufferedOutputStream;
5
import java.io.File;
6
import java.io.FileInputStream;
7
import java.io.IOException;
8
import java.util.List;
9
import java.util.UUID;
10
import javax.servlet.http.HttpServletResponse;
11
import org.apache.commons.io.FileUtils;
12
import org.apache.commons.lang3.StringUtils;
13
import org.apache.struts2.ServletActionContext;
14
import org.springframework.beans.factory.annotation.Autowired;
15
import com.opensymphony.xwork2.ActionSupport;
16
import com.tax.pojo.nsfw.User;
17
import com.tax.service.UserService;
18
19
/**
20
* UserAction
21
* @author ZENG.XIAO.YAN
22
* @date 2017年7月11日 上午10:06:05
23
* @version v1.0
24
*/
25
26
public class UserAction extends ActionSupport {
27
28
private static final long serialVersionUID = 4526496105243102063L;
29
30
private UserService userService;
31
private User user;
32
/** 文件上傳的3個屬性 */
33
private File headImg; // 這個名字和表單的name的值一樣
34
private String headImgFileName;
35
private String headImgContentType;
36
/** 存放圖片的本地文件夾 */
37
private static final String USER_IMAGE_DIR = "D:/upload";
38
39
40
41
/**
42
* 展示用戶頭像 Action方法
43
* @return 將頭像輸出到頁面
44
* @see 訪問方式:tax/nsfw/user_showHeadImg.action?user.id=xxxx
45
*/
46
public String showHeadImg() {
47
// 這個user的id是通過前台傳過來的
48
if(null != user && user.getId() != null) {
49
// 通過用戶id去數據庫查找出用戶頭像的地址
50
String img = userService.findById(user.getId()).getHeadImg();
51
if(StringUtils.isNotBlank(img)) {
52
// 拼接成本地地址,如:D:/upload/user/0dc14d2b81444ce1b5600a3fe43f9f30.jpg
53
// USER_IMAGE_DIR = D:/upload
54
// img 如:user/0dc14d2b81444ce1b5600a3fe43f9f30.jpg
55
File imgFile = new File(USER_IMAGE_DIR + "/" + img);
56
// 如果圖片文件存在,就輸出到頁面
57
if(imgFile.exists()) {
58
/** 獲取HttpServletResponse */
59
HttpServletResponse response = ServletActionContext.getResponse();
60
/** 設置響應的內容類型 */
61
response.setContentType("images/jpeg");
62
/** 以下3行代碼用於設置禁止瀏覽器緩存該圖片 */
63
response.setDateHeader("expries", -1);
64
response.setHeader("Cache-Control", "no-cache");
65
response.setHeader("Prama", "no-cache");
66
// 以下為IO流操作
67
BufferedInputStream bis = null;
68
BufferedOutputStream bos = null;
69
try {
70
bis = new BufferedInputStream(new FileInputStream(imgFile));
71
// 這個Response.getOutputStream()是用於輸出到瀏覽器的輸出流
72
bos = new BufferedOutputStream(response.getOutputStream());
73
byte[] buffer = new byte[1024];
74
int len = 0;
75
while ((len = bis.read(buffer)) != -1) {
76
bos.write(buffer, 0, len);
77
}
78
} catch (Exception e) {
79
e.printStackTrace();
80
} finally {
81
// 關流
82
if (bis != null) {
83
try {
84
bis.close();
85
} catch (IOException e) {
86
e.printStackTrace();
87
}
88
}
89
if (bos != null) {
90
try {
91
bos.close();
92
} catch (IOException e) {
93
e.printStackTrace();
94
}
95
}
96
}
97
}
98
}
99
}
100
// 這里沒有返回視圖,直接返回NONE
101
return NONE;
102
}
103
104
105
106
107
108
/**
109
* 專門用於文件上傳的方法,返回文件路徑
110
* @return 文件路徑
111
*/
112
private String uploadFile() {
113
try {
114
if (null != headImg) {
115
// 獲取存放文件夾路徑
116
// USER_IMAGE_DIR = D:/upload
117
String prePath = USER_IMAGE_DIR.concat("/user");
118
if(!new File(prePath).exists()) {
119
new File(prePath).mkdirs();
120
}
121
// 新的文件名
122
String fileName = UUID.randomUUID().toString().replaceAll("-", "")
123
.concat(headImgFileName.substring(headImgFileName.lastIndexOf(".")));
124
// 用common-io.jar的工具copy文件
125
FileUtils.copyFile(headImg, new File(prePath,fileName));
126
return "user/".concat(fileName);
127
}
128
} catch (IOException e) {
129
e.printStackTrace();
130
}
131
return null;
132
}
133
134
135
/** setter and getter method */
136
137
public User getUser() {
138
return user;
139
}
140
141
public void setUser(User user) {
142
this.user = user;
143
}
144
145
public File getHeadImg() {
146
return headImg;
147
}
148
149
public void setHeadImg(File headImg) {
150
this.headImg = headImg;
151
}
152
153
public String getHeadImgFileName() {
154
return headImgFileName;
155
}
156
157
public void setHeadImgFileName(String headImgFileName) {
158
this.headImgFileName = headImgFileName;
159
}
160
161
public String getHeadImgContentType() {
162
return headImgContentType;
163
}
164
165
public void setHeadImgContentType(String headImgContentType) {
166
this.headImgContentType = headImgContentType;
167
}
168
169
}