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 ...
随机推荐
- python 以单例模式封装logging相关api实现日志打印类
python 以单例模式封装logging相关api实现日志打印类 by:授客QQ:1033553122 测试环境: Python版本:Python 2.7 实现功能: 支持自由配置,如下lo ...
- Android 监听手机GPS打开状态
转载请标明出处:http://blog.csdn.net/zhaoyanjun6/article/details/70854942 本文出自[赵彦军的博客] GPS_Presenter package ...
- 【three.js练习程序】拖动选中的物体
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title> ...
- the database needs something to populate existing rows.
这是我在使用Django进行models编写时的一个错误. 解决办法: 为其指定一个默认值即可 object_id = models.CharField(max_length=50, default= ...
- Java语法基础(四)----循环结构语句
一.循环结构: 循环语句可以在满足循环条件的情况下,反复执行某一段代码,这段被重复执行的代码被称为循环体语句,当反复执行这个循环体时,需要在合适的时候把循环判断条件修改为false,从而结束循环,否则 ...
- gulp学习。
安装gulp 安装gulp之前必须先安装node.js,然后在命令行里输入 $ npm install gulp-cli -g (-g 表示全局安装)然后在输入$ gulp -v ,验证,安装完成后再 ...
- CSS揭秘(二)背景与边框
Chapter2 背景与边框 1. 半透明边框 基础:了解 RGBA & HSLA 颜色(色调 0~360.饱和度.亮度 (0%黑色~100%白色).透明度) 默认情况下,背景在边框的下层,容 ...
- 【SPL标准库专题(7)】 Datastructures:SplHeap & SplMaxHeap & SplMinHeap
堆(Heap)就是为了实现优先队列而设计的一种数据结构,它是通过构造二叉堆(二叉树的一种)实现.根节点最大的堆叫做最大堆或大根堆,根节点最小的堆叫做最小堆或小根堆.二叉堆还常用于排序(堆排序). 类摘 ...
- 一般处理程序HttpHandler的应用
ashx 一般处理程序(HttpHandler)是·NET众多web组件的一种,ashx是其扩展名.一个httpHandler接受并处理一个http请求,类比于Java中的servlet.类比于在Ja ...
- jquery.validate,错误信息位置
好长时间没有用jquery.validate.js这个插件了,忘得差不多了.唉,好东西还是要经常拿出来看看的,今天用jquery.validate来做一个小东西,遇到一个问题,就是错误提示信息的位置问 ...