开发中遇到这么一个要求,用户USER这个PO里需要保存用户的照片。一般情况下有两种处理方法: iW/ fh\
一是直接保存图片到数据库;二是保存图片到服务器端,PO字段保存一个联接。考虑到用户照片 V/:39V
一般较小,采用第一种方法。 7o}yvmX18
public class User extends Principal { ;M3G
private byte[] photo; //考虑与各种数据库兼容问题 9&3e9b*J
public byte[] getPhoto() { ^{UZ(b#
return photo; @k 8:#N
} g,e=!F7_
r 8mV}Z
public void setPhoto(byte[] photo) { i#VE0er\
this.photo = photo; /e1?3y:L
} t_e2]=wlL
.............. 1V"wl
} ,4 1-
页面里面,直接用webwork的FileUploadInterceptor拦截 ')?0*#
<@ww.form enctype="multipart/form-data" action="doUpdateUser" method="post"> g&xw)W9p
<image name="img1" src="/getUserPhoto.action?userId=${user.id}" width=90 height=120 border="0"></image> gz_rGA,
<@ww.file label="%{getText('user.photo')}" name="photo" /> |K! j!Ra=
</@ww.form> DY5~[
xwork.xml里的配置 =MQu2NchJ5
<action name="doUpdateUser" class="com.eway.framework.organization.action.OrganizationAction" method="updateUser"> 2`&1(W/P
<interceptor-ref name="defaultStack"> l?,0N1W,
<param name="fileUpload.allowedTypes"> Z9 M}e@x|
image/x-png,image/gif,image/pjpeg Ft:&4O_5z
</param> 5:*4eqz
</interceptor-ref> _ ^PO_\YQ%
<result name="success">/organization/user.ftl</result> fD#3l
</action> [QjQ?0y+y
,,Xu'r7v=
<action name="getUserPhoto" class="com.eway.framework.organization.action.OrganizationAction" method="getUserPhoto"> 8tr@ ,5
<result>/organization/user.ftl</result> 1w:!>[%
</action> r@BMNU7bi
引用默认的拦截器栈,栈里已经包含FileUploadInterceptor拦截,这里配置FileUploadInterceptor拦截的参数,设定上传的文件为图片 &FRRVc>#
格式 w%$Z;_[r=
Action类 :$ZGDJD.
public class OrganizationAction extends BaseOrganizationAction{ {T3(SJd
private File photo; //与页面里的上传文件字段名对应 ]Hi=Zr
private OutputStream outPhoto T m@"
Q Z9X)zT
/** 2>&!r!Z
* 更新用户信息 7fb e5a[|
* DkvCM{M{(
* @return M jVt B4
* @throws Exception - QnC=f
*/ $@*3k"kI
public String updateUser() throws Exception { YJ#==3V$=&
//以下为保存图片,视情况修改 n > s~Ac|
if (null != photo) { P><="s
FileInputStream file = new FileInputStream(photo); ~hn|-zV&
int length = file.available(); KhC%2dH
byte[] buffer = new byte[length]; 3f@ $)
file.read(buffer); >(x-Kpc
file.close(); 6~Z+g3x3
user.setPhoto(buffer); //将上传的图片转换为字节数组存储到PO中 bflX\xx7
} @Kk x:zFP
organizationService.updateUser(user); u#dTN$
return SUCCESS; 50;341z
} I Z(zKt<
:\ nu4,x
public String getUserPhoto() throws Exception { f $ae@
user = organizationService.getUserById(userId); ]NjRMf&! {
if (user.getPhoto() != null) { #(Se#i^(x
outPhoto = this.getResponse().getOutputStream(); //将PO中字节数组转换为输出流 rEE/ `v
outPhoto.write(user.getPhoto()); _p~b1iDmZ
outPhoto.flush(); 1A: 4S@
outPhoto.close(); )jY8=kW
} ?XS3h0"=V
return SUCCESS; ImMI+(
} ymYl5Lef
} F,fX0-
这样就OK了,考虑一个问题,就是action 必须要指定一个result ,实际这里的图片显示仅仅是要一个输出流 8-a=ZFe
<image name="img1" src="/getUserPhoto.action?userId=${user.id}" width=90 height=120 border="0"></image> 6-wfT'x
而我的配置里面是 \qZXqIE
<result>/organization/user.ftl</result> -\[TxT:gF
不知道这会不会有什么影响。或者这样? w0,d!B
<result>/organization/blank.ftl</result>
查看本文来源