博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Struts2文件上传实例
阅读量:7220 次
发布时间:2019-06-29

本文共 4416 字,大约阅读时间需要 14 分钟。

(1)上传表单

       这里需要注意的是想要上传文件,form表单的的类型必须是:enctype=”multipart/form-data”,比如说这样:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
<
s:form 
action
=
"toAddGoods" 
method
=
"post" 
namespace
=
"/goods" 
enctype
=
"multipart/form-data"
>     
            
<
table 
id
=
"advEdit" 
width
=
"380" 
height
=
"66"
>
                
<
tr
>               
                  
<
td
><
s:textfield 
name
=
"goods.goodsName" 
label
=
"商品名称" 
/></
td
>
                
</
tr
>
                
<
tr
>               
                  
<
td
><
s:textfield 
name
=
"goods.goodsPrice" 
label
=
"起拍价格" 
/></
td
>
                
</
tr
>            
                
<
tr
>
                  
<
td
><
s:textfield 
name
=
"goods.goodsDesc" 
label
=
"商品描述" 
/></
td
>
                
</
tr
>
                
<
tr
>
                  
<
td
><
s:file 
name
=
"goodsImage" 
label
=
"商品图片"
></
s:file
></
td
>
                
</
tr
>
                
<
tr
>
                  
<
td
><
s:submit 
styleClass
=
"btn" 
value
=
"添加" 
align
=
"center" 
/></
td
>
                
</
tr
>
            
</
table
>
        
</
s:form
>

(2)配置struts.xml :

这里需要添加一个名为“fileUpload”的interceptor-ref,主要是对上传文件的格式和大小进行过滤

i)package是这样定义的:

1
<
package 
name
=
"goods" 
namespace
=
"/goods" 
extends
=
"struts-default"
>

ii)action是这样的:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
<
action 
name
=
"toAddGoods" 
class
=
"goods" 
method
=
"toAddGoods"
>
            
<
result 
name
=
"input"
>/addgoods.jsp</
result
>
            
<
result 
name
=
"index" 
type
=
"redirect"
>/index.jsp</
result
>
            
<
result 
name
=
"login" 
type
=
"redirect"
>/index.jsp</
result
>
             
            
<
interceptor-ref 
name
=
"fileUpload"
>
                
<!-- 文件过滤 -->
                
<
param 
name
=
"allowedTypes"
>image/bmp,image/png,image/gif,image/jpeg</
param
>
                
<!-- 文件大小, 以字节为单位 -->
                
<
param 
name
=
"maximumSize"
>4194304</
param
>
            
</
interceptor-ref
>
            
<
interceptor-ref 
name
=
"defaultStack" 
/>
 
        
</
action
>

注:class没有写action类的完整路径是因为我引入了spring,action类的完整路径通过<bean>标签配置在applicationContext.xml文件中

1
2
3
<
bean 
id
=
"goods" 
class
=
"com.zxpm.action.GoodsAction" 
scope
=
"prototype"
>
        
<
property 
name
=
"goodsBiz" 
ref
=
"goodsBiz" 
/>
    
</
bean
>

(3)action的实现:

1
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
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
package 
com.zxpm.action;
 
import 
java.io.File;
import 
java.io.IOException;
import 
java.text.SimpleDateFormat;
import 
java.util.Date;
import 
java.util.List;
import 
java.util.Map;
import 
java.util.Random;
 
import 
org.apache.commons.io.FileUtils;
import 
org.apache.struts2.ServletActionContext;
 
import 
com.opensymphony.xwork2.ActionContext;
import 
com.opensymphony.xwork2.ActionSupport;
import 
com.zxpm.biz.GoodsBiz;
import 
com.zxpm.entity.Goods;
import 
com.zxpm.entity.Users;
 
public 
class 
GoodsAction 
extends 
ActionSupport{
    
private 
Goods goods;  
//用于封装参数
    
private 
GoodsBiz goodsBiz;  
    
private 
File goodsImage;
    
private 
String fileName;  
//上传的临时文件的文件名
     
    
public 
Goods getGoods() {
        
return 
goods;
    
}
 
    
public 
void 
setGoods(Goods goods) {
        
this
.goods = goods;
    
}
 
    
public 
void 
setGoodsBiz(GoodsBiz goodsBiz) {
        
this
.goodsBiz = goodsBiz;
    
}
     
    
public 
void 
setGoodsImage(File goodsImage) {
        
this
.goodsImage = goodsImage;
    
}
    
//得到文件名
    
public 
void 
setGoodsImageFileName(String fileName){
        
this
.fileName = fileName;
    
}
 
    
//省略。。。
     
    
/**
     
* 添加新拍卖商品
     
* */
    
public 
String toAddGoods(){
        
//1 保存上传的文件
        
String targetDirectory = ServletActionContext.getServletContext().getRealPath(
"/uploadImages"
);
        
String targetFileName = renameImage(fileName);  
//新的文件名
        
File target = 
new 
File(targetDirectory,targetFileName);  
//保存的新文件
        
try 
{
            
FileUtils.copyFile(goodsImage, target);
        
catch 
(IOException e) {
            
e.printStackTrace();
        
}
        
// 2 保存新商品描述信息
        
goods.setGoodsPic(targetFileName);
        
Map<String, Object> session = ActionContext.getContext().getSession();
        
Users saler = (Users) session.get(
"user"
);
        
goods.setSaler(saler);
        
goods.setBuyer(saler);
        
goods.setGoodsStatus(
0
);
         
        
goodsBiz.addGoods(goods);
         
        
return 
"index"
;
    
}
     
    
/**
     
* 文件重命名
     
* */
    
public 
String renameImage(String fileName){
        
String formatDate = 
new 
SimpleDateFormat(
"yyMMddHHmmss"
).format(
new 
Date());  
//当前时间字符串
        
int 
random = 
new 
Random().nextInt(
10000
);
        
String extension = fileName.substring(fileName.lastIndexOf(
"."
));  
//文件后缀
         
        
return 
formatDate + random + extension;
    
}
     
    
//省略。。。
}

注:i)这里定义的File类型变量goodsImage实际上是上传的临时文件的File对象,私有属性fileName就是上传文件的原始文件名,然后使用setter方法进行赋值。之所以这样做,是因为使用goodsImage.getName()获取到的文件后缀不是上传的文件的真实后缀,仅仅只是xxx.tmp

ii)ServletActionContext.getServletContext().getRealPath(“/uploadImages”);是获取想要保存的路径在磁盘上的绝对路径

iii)这里使用了FileUtils这个开源组件来保存文件,而不是自己手动写IO流,理由很简单:方便快速

iv)为了避免上传的文件多了造成文件名重复,同时为了增大“黑客”攻击的难度,因此统一将上传的文件进行重命名,采用当前时间+几位随机数组成的字符串的形式

(4)结果:

我这里效果是这样的:

本文转自 pangfc 51CTO博客,原文链接:http://blog.51cto.com/983836259/1741571,如需转载请自行联系原作者

你可能感兴趣的文章
[LeetCode] Different Ways to Add Parentheses 添加括号的不同方式
查看>>
Atom 检测php错误扩展linter-php
查看>>
ubuntu下msmtp+mutt的安装和配置
查看>>
第 13 章 sar - System Activity Reporter
查看>>
第 70 章 Oracle 监控
查看>>
vlc相关学习资料汇总及零散技术总结
查看>>
Intellij IDEA 14使用maven3.3.3 问题
查看>>
Java 进制转换
查看>>
Code: UrlBuilder class in JavaScript
查看>>
[LintCode] Best Time to Buy and Sell Stock 买卖股票的最佳时间
查看>>
Android中文合集(5)(126+8篇)(chm格式)
查看>>
解读|百分点凭啥能推出「中国首个行业AI决策系统」
查看>>
Debian里编译内核
查看>>
WPF/E 我将怎么拥抱你?困惑与期待
查看>>
使用python玩跳一跳超详细使用教程
查看>>
js中push(),pop(),unshift(),shift()的用法
查看>>
WinForm界面开发之“OutLookBar”工具条
查看>>
iOS - OC NSDate 时间
查看>>
Netty重要概念介绍
查看>>
matcaffe的blob维度顺序
查看>>