開發中遇到這么一個要求,用戶USER這個PO里需要保存用戶的照片。一般情況下有兩種處理方法:一是直接保存圖片到數據庫;二是保存圖片到服務器端,PO字段保存一個聯接。考慮到用戶照片一般較小,采用第一種方法。
?1
public
?
class
?User?
extends
?Principal?
{
?2
????
private
?
byte
[]?photo;???
//
考慮與各種數據庫兼容問題
?3
????
public
?
byte
[]?getPhoto()?
{
?4
????????
return
?photo;
?5
????}
?6
?7
????
public
?
void
?setPhoto(
byte
[]?photo)?
{
?8
????????
this
.photo?
=
?photo;
?9
????}
10
????


..
11
}
12



?2

?3



?4

?5

?6

?7



?8

?9

10





11

12

頁面里面,直接用webwork的FileUploadInterceptor攔截




xwork.xml里的配置














引用默認的攔截器棧,棧里已經包含FileUploadInterceptor攔截,這里配置FileUploadInterceptor攔截的參數,設定上傳的文件為圖片
格式
Action類
?1
public
?
class
?OrganizationAction?
extends
?BaseOrganizationAction
{
?2
????
private
?File?photo;??
//
與頁面里的上傳文件字段名對應
?3
????
private
?OutputStream?outPhoto
?4
?5
?????
/**?*/
/**
?6
?????*?更新用戶信息
?7
?????*
?8
?????*?
@return
?9
?????*?
@throws
?Exception
10
?????
*/
11
????
public
?String?updateUser()?
throws
?Exception?
{
12
????????
//
以下為保存圖片,視情況修改
13
????????
if
?(
null
?
!=
?photo)?
{
14
????????????FileInputStream?file?
=
?
new
?FileInputStream(photo);
15
????????????
int
?length?
=
?file.available();
16
????????????
byte
[]?buffer?
=
?
new
?
byte
[length];
17
????????????file.read(buffer);
18
????????????file.close();
19
????????????user.setPhoto(buffer);???
//
將上傳的圖片轉換為字節數組存儲到PO中
20
????????}
21
????????organizationService.updateUser(user);
22
????????
return
?SUCCESS;
23
????}
24
25
????
public
?String?getUserPhoto()?
throws
?Exception?
{
26
????????user?
=
?organizationService.getUserById(userId);
27
????????
if
?(user.getPhoto()?
!=
?
null
)?
{
28
????????????outPhoto?
=
?
this
.getResponse().getOutputStream();?
//
將PO中字節數組轉換為輸出流
29
????????????outPhoto.write(user.getPhoto());
30
????????????outPhoto.flush();
31
????????????outPhoto.close();
32
????????}
33
????????
return
?SUCCESS;
34
????}
35
}
36



?2

?3

?4

?5


?6

?7

?8

?9

10

11



12

13



14

15

16

17

18

19

20

21

22

23

24

25



26

27



28

29

30

31

32

33

34

35

36

這樣就OK了,考慮一個問題,就是action 必須要指定一個result ,實際這里的圖片顯示僅僅是要一個輸出流


而我的配置里面是

不知道這會不會有什么影響。或者這樣?

http://www.aygfsteel.com/ronghao 榮浩原創,轉載請注明出處:)