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

一、思路

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

二、代码

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

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


Struts2将图片输出到页面的更多相关文章

  1. ASP.NET 画图与图像处理-如何直接输出到页面

    有时候我们生成的图片并不需要保存到磁盘中,而是直接输出到页面,比如验证码.实时报表等,如何做呢?请参考如下:     protected void Page_Load(object sender, E ...

  2. 使用IExport进行图片输出出现File creation error

    使用IExport进行图片输出(.JPG)时,出现如下异常File creation error.   在ESRI.ArcGIS.Output.ExportJPEGClass.FinishExport ...

  3. js引入php 用来加载静态页面 输出到页面中

    HTML页面中加入代码 <script type="text/javascript" src="http://www.域名.com/js.php?id=tjyd&q ...

  4. 动态jsp页面转PDF输出到页面

    最近工作中遇到不少问题.总结一下.这段代码主要功能是将一个生成JSP页面转发成PDF输出到页面 需要利用ITEXT String html = ServletUtils.forward(request ...

  5. JavaScript-2.2 document.write 输出到页面的内容

    <html> <head> <meta http-equiv="content-type" content="text/html;chars ...

  6. Struts2如何传值到jsp页面

    Struts2如何传值到jsp页面 不是action传值到jsp页面,而是jsp页面获取action中的属性值,或者范围(如request,session,application等)里的值.所以,有两 ...

  7. 【PDF单页转化为图片输出 注意:英文或图片类的PDF可转化,中文抛异常】

    public static void main(String[] args) throws IOException { /** * PDF单页转化为图片输出 注意:英文或图片类的PDF可转化,中文抛异 ...

  8. jstl-按照html的形式输出至页面

    一.按照html的形式输出至页面 <c:out value="${xxx}" default="默认值" escapeXml="false&qu ...

  9. webpack2.0 css文件引入错误解决及图片输出在根目录配置问题

    webpack引入css文件,main.js内容如下 import Vue from 'vue'; import App from './App.vue'; import Mint from 'min ...

随机推荐

  1. Flink1.4.0连接Kafka0.10.2时遇到的问题

    Flink1.4.0连接部署在Linux上的Kafka0.10.2时,报如下异常: org.apache.flink.streaming.connectors.kafka.FlinkKafkaCons ...

  2. JS截取字符串方法实例

    // JS截取字符串可使用 substring()或者slice() // // 函数:substring() // 定义:substring(start,end)表示从start到end之间的字符串 ...

  3. 重学C语言---05运算符、表达式和语句

    一.循环简介 实例程序 /*shoes1.c--把一双鞋的尺码变为英寸*/#include <stdio.h>#define ADJUST 7.64#define SCALE 0.325 ...

  4. Mongodb集群——master/slave

    集群的配置 (本测试放于同一台机器进行配置,所以IP地址一样,如果是在不同的服务器上更换IP便可以)   1.目录结构       拷贝两份mongodb到/home/scotte.ye/mongo1 ...

  5. win Server 2008 笔记

    1.开启tsmmc 远程登录连接 需要在入站规则中启用一下规则 远程管理(RPC-EPMAP) 远程管理(RPC) 远程管理(RPCNP-IN) 远程管理(TCP-IN) 远程管理 - RemoteF ...

  6. SQL Server 从2000复制数据到2008及以上版本的一种方法

    1.通过Linked Servers 执行sql出现错误提示,无法执行复制数据操作. sql: insert into tb_User select from [**.**.*.**].DB.dbo. ...

  7. ajax status 错误

    status **:未被始化 status **:请求收到,继续处理 status **:操作成功收到,分析.接受 status **:完成此请求必须进一步处理 status **:请求包含一个错误语 ...

  8. Android external扩展工程

    Android的扩展工程包含在external文件夹中,这是一些经过修改后适应Android系统的开源工程,这些工程有些在主机上运行,有些在目标机上运行: 工程名称  工程描述  aes  高级加密标 ...

  9. win7X64位安装mysql-5.7.16

    今天尝试在win7系统中安装mysql,发现过程有点复杂,不过还好已经成功安装,写个博客纪念一下,顺便可以帮助大家. 1.在官网上面下载mysql, 注意:一定要下载对应的版本,第一次下载的是最下面一 ...

  10. November 07th, 2017 Week 45th Tuesday

    Love is composed of a single soul inhabiting two bodies. 爱就是一个灵魂栖息在两个身体里. Love and family and childr ...