Struts2将图片输出到页面
一、思路
二、代码
<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>
<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>
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;
}
}
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;
}
}
Struts2将图片输出到页面的更多相关文章
- ASP.NET 画图与图像处理-如何直接输出到页面
有时候我们生成的图片并不需要保存到磁盘中,而是直接输出到页面,比如验证码.实时报表等,如何做呢?请参考如下: protected void Page_Load(object sender, E ...
- 使用IExport进行图片输出出现File creation error
使用IExport进行图片输出(.JPG)时,出现如下异常File creation error. 在ESRI.ArcGIS.Output.ExportJPEGClass.FinishExport ...
- js引入php 用来加载静态页面 输出到页面中
HTML页面中加入代码 <script type="text/javascript" src="http://www.域名.com/js.php?id=tjyd&q ...
- 动态jsp页面转PDF输出到页面
最近工作中遇到不少问题.总结一下.这段代码主要功能是将一个生成JSP页面转发成PDF输出到页面 需要利用ITEXT String html = ServletUtils.forward(request ...
- JavaScript-2.2 document.write 输出到页面的内容
<html> <head> <meta http-equiv="content-type" content="text/html;chars ...
- Struts2如何传值到jsp页面
Struts2如何传值到jsp页面 不是action传值到jsp页面,而是jsp页面获取action中的属性值,或者范围(如request,session,application等)里的值.所以,有两 ...
- 【PDF单页转化为图片输出 注意:英文或图片类的PDF可转化,中文抛异常】
public static void main(String[] args) throws IOException { /** * PDF单页转化为图片输出 注意:英文或图片类的PDF可转化,中文抛异 ...
- jstl-按照html的形式输出至页面
一.按照html的形式输出至页面 <c:out value="${xxx}" default="默认值" escapeXml="false&qu ...
- webpack2.0 css文件引入错误解决及图片输出在根目录配置问题
webpack引入css文件,main.js内容如下 import Vue from 'vue'; import App from './App.vue'; import Mint from 'min ...
随机推荐
- 【转】C++11的enum class & enum struct和enum
转自:https://blog.csdn.net/sanoseiichirou/article/details/50180533 C++标准文档——n2347(学习笔记) 链接:http://www. ...
- Git仓库初始化与推送到远端仓库
以下命令为Git仓库初始化,添加远端代码托管仓库,以及推送到远端仓库的命令. 以 "github.com"为远端仓库做示例 # Git 库初始化 git init # 将文件添加到 ...
- LeetCode 题解之 Positions of Large Groups
1.题目描述 2.问题分析 从头遍历字符串,使用一个局部迭代器和局部变量记录该字符个数.如果个数>= 3 ,则将此时的迭代器位置和局部迭代器的位置保存到局部vector中.再将这个局部vecto ...
- SendMessage,BroadcastMessage
三者比较 用于向某个GameObject发送一条信息,让它完成特定功能.其实本质是调用绑定GameObject里面的Script里面的函数,可以跨语言的,例如Javascript可以调用C#的函数,我 ...
- 学习python 第一章
目录 第一章... 1 1:新建项目... 1 2:修改默认模板... 3 3:什么是变量... 3 4:重指向... 3 5:常量的表示... 4 6:格式化输出(三种方法)... 4 7:打印一个 ...
- Javaweb学习(二):Http通信协议
当我们开始jsp/servlet编程之旅之前,我们还需要知道一些关于网络通讯方面的一些知识.这样能更加有助于我们的理解,希望大家能看懂我的描述,而不至于在学习的路上一知半解.(手动比❤) 认识Ht ...
- gdb调试:
1 简介 GDB(GNU Debugger)是GCC的调试工具.其功能强大,现描述如下: GDB主要帮忙你完成下面四个方面的功能: 1.启动你的程序,可以按照你的自定义的 ...
- System.IO.Path文件路径类
Path类的静态属性和方法,此类操作不影响物料文件. 属性 char a = System.IO.Path.VolumeSeparatorChar;//: char b = System.IO.Pat ...
- console.time方法与console.timeEnd方法
在Node.js中,当需要统计一段代码的执行时间时,可以使用console.time方法与console.timeEnd方法,其中console.time方法用于标记开始时间,console.time ...
- Maven 安装源码和文档到本地仓库
一: 1: mvn source:jar 生成源码的jar包 2: mvn source:jar install 将源码安装到本地仓库 ,可以直接mvn source:jar install 一部 ...