Struts2将图片输出到页面

时间:2023-03-09 19:48:50
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>
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
    @Autowired
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
}