Struts2中文件上传的两种方式

Struts2中的文件上传,方式很多,大体原理不变。一种是通过POST请求上传,另一种Struts2封装好的字段驱动的方式上传。


1.第一种:

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
public  String uploadImage() {
         boolean  result =  false ;
         /**
         *获取request对象,在Struts2或者Servlet中同理
         */
         HttpServletRequest req = ServletActionContext.getRequest();
         DiskFileItemFactory factory =  new  DiskFileItemFactory();
         factory.setRepository( new  File(getUploadFileSavePath(req)));
         factory.setSizeThreshold( 1024  1024  2 );
                                                                                                                                                                                                                                                                
         ServletFileUpload upload =  new  ServletFileUpload(factory);
         List<?> items =  null ;
         try  {
             items = upload.parseRequest(req);
         catch  (FileUploadException e1) {
             e1.printStackTrace();
         }
         for  ( int  i =  0 ; i < items.size(); i++) {
             FileItem item = (FileItem) items.get(i);
             if  (item.isFormField()) {
                 continue ;
             else  {
                 String fileName = item.getName();
                 /**
                 *StringUtils工具生成时间戳作为文件名,可扩展
                 */
                 String dstFile = StringUtils.timeStamp()
                         + fileName.substring(fileName.lastIndexOf( '.' ));
                 String dstFileName = getUploadFileSavePath(req)
                         + File.separator + dstFile;
                 FileOutputStream fos;
                 try  {
                     fos =  new  FileOutputStream(dstFileName);
                     if  (item.isInMemory()) {
                         InputStream in;
                         in = item.getInputStream();
                         byte [] btn =  new  byte [ 1024 ];
                         int  size;
                         while  ((size = in.read(btn)) >  0 ) {
                             fos.write(btn,  0 , size);
                         }
                         in.close();
                         fos.close();
                     }
                 catch  (FileNotFoundException e) {
                     e.printStackTrace();
                 catch  (IOException e) {
                     e.printStackTrace();
                 }
             }
         }
     }

依赖的上传组件是:org.apache.commons.fileupload

原理:通过请求来判断Form中的字段类型,属于文件类型则上传文件。

2.第二种:

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
87
88
public  class  UploadAction  extends  ActionSupport {
     private  static  final  long  serialVersionUID = 7545315675701301471L;
     /**
      * 上传文件
      */
     private  File ccImage;
     /**
      * 下面的两个字段因ccImage字段存在,而且命名分别是xxxContentType,xxxFileName
      */
     /**
      * 文件类型(Meta信息)
      */
     private  String ccImageContentType;
     /**
      * 上传的文件名
      */
     private  String ccImageFileName;
     private  HttpServletRequest request = ServletActionContext.getRequest();
     /**
      * 获取工程的访问URL根路径:例如:http://127.0.0.1:8080/工程名
      */
     private  String basePath = request.getScheme() +  "://"
             + request.getServerName() +  ":"  + request.getServerPort()
             + request.getContextPath();
     /**
      * 上传文件
      *
      * @return
      */
     public  String upload() {
         boolean  result =  false ;
         String dstFile = StringUtils.timeStamp()
                 + ccImageFileName.substring(ccImageFileName.lastIndexOf( '.' ));
         String dstFileName = getUploadFileSavePath() + File.separator + dstFile;
         File destFile =  new  File(dstFileName);
         try  {
             FileUtils.copyFile(ccImage, destFile);
         catch  (IOException e) {
             e.printStackTrace();
         }
         return  result ? Action.SUCCESS : Action.ERROR;
     }
     /**
      * 获取上传文件的路径
      *
      * @return
      */
     private  String getUploadFileSavePath() {
         @SuppressWarnings ( "deprecation" )
         /**
          * Const.UPLOAD_HEAD_PATH:可配置的变量
          */
         String path = request.getRealPath(Const.UPLOAD_HEAD_PATH);
         File dir =  new  File(path);
         if  (!dir.exists()) {
             dir.mkdirs();
         }
         return  path;
     }
     /**
      * Struts2对于上传文件进行了封装,set方法必须存在,通过set方法和为字段进行赋值
      * @return
      */
     public  String getCcImageContentType() {
         return  ccImageContentType;
     }
     public  void  setCcImageContentType(String ccImageContentType) {
         this .ccImageContentType = ccImageContentType;
     }
     public  File getCcImage() {
         return  ccImage;
     }
     public  void  setCcImage(File ccImage) {
         this .ccImage = ccImage;
     }
     public  String getCcImageFileName() {
         return  ccImageFileName;
     }
     public  void  setCcImageFileName(String ccImageFileName) {
         this .ccImageFileName = ccImageFileName;
     }
     public  String getBasePath() {
         return  basePath;
     }
     public  void  setBasePath(String basePath) {
         this .basePath = basePath;
     }
}

上面的UploadAction类中的属性有File,String其中后两个属性因为第一个属性存在而存在,有一定的关联性,这里既可以看成是属性驱动,也可以是模型驱动。Struts2对文件上传的这个过程进行了很好的封装,这里注意属性的命名和set方法即可。

Struts上传文件配置:

1
2
<!-- 指定允许上传的文件最大字节数。默认值是2097152(2M) -->
< constant  name = "struts.multipart.maxSize"  value = "2097152"  />

Action的配置

1
2
3
4
< interceptor-ref  name = "fileUpload" >
     < param  name = "allowedTypes" >image/bmp,image/png,image/gif,image/jpeg</ param >
</ interceptor-ref >
< interceptor-ref  name = "defaultStack"  />

关于Struts的文件上传拦截器参见类:

org.apache.struts2.interceptor.FileUploadInterceptor


末了:写这篇文章,不在内容,在意义,在开发中上传文件遇到了一些问题,百度了一下,很多都是泊来品,于是回到官方文档,很多问题都是能解决了,纪念一下,警示自己少百度,少谷歌,溯本逐源才能做好真学问。



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

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值