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,如需转载请自行联系原作者

相关文章
|
3月前
|
存储 人工智能 JavaScript
OpenClaw/Clawdbot指南:阿里云上及本地部署+国内适配工具skills,告别水土不服
2026年,OpenClaw(原Clawdbot,曾用名Moltbot)凭借本地私有化运行、高度可扩展的核心优势,成为AI智能体领域的热门工具。但不少国内用户在使用时遭遇“水土不服”——官方仅支持Discord、Telegram等海外通讯工具,原生技能库覆盖不足,自建部署维护成本高等问题。
1919 2
|
监控
idea插件报错导致不能启动的处理技巧
在安装IDEA的插件时,难免会遇到插件不合理导致的IDEA启动时报错,没有办法从IDEA的plugins管理面板卸载插件,那怎么办呢? 答:手动删除。查找IDEA的日志C:\Users\{username}\.IntelliJIdea2016.1\system\log\idea.log,启动IDEA并监控该日志行为及报错信息;然后在电脑上安装Everything (该工具可
6750 1
|
机器学习/深度学习 存储 人工智能
大模型综述
本文是一篇关于大模型的综述文章,旨在帮助读者快速了解并深入研究大模型的核心概念和技术细节。
2215 11
Vue3文本域(Textarea)
这是一个基于 Vue3 的可自定义文本域组件 (`Textarea`),具备多种实用功能,如自适应内容高度、清除图标、字数统计及禁用状态等。
690 2
Vue3文本域(Textarea)
|
Java 开发工具 对象存储
PAI-AutoLearning 图像分类使用教程
PAI AutoLearning(简称PAI AL)自动学习支持在线标注、自动模型训练、超参优化以及模型评估。在平台上只需准备少量标注数据,设置训练时长即可得到深度优化的模型。同时自动学习PAI AL平台与EAS模型在线服务打通,一键完成模型部署。下面通过一个番茄(tomato)和黄瓜(cucumber)的图片分类示例来演示整个流程的实现具体操作实现步骤。
14013 0
PAI-AutoLearning 图像分类使用教程
|
存储 算法 前端开发
一文带你学会国产加密算法SM4的java实现方案
今天给大家带来一个国产SM4加密解密算法的java后端解决方案,代码完整,可以直接使用,希望给大家带来帮助,尤其是做政府系统的开发人员,可以直接应用到项目中进行加密解密。
4498 1
|
监控 数据挖掘 数据安全/隐私保护
ERP系统中的绩效管理与考核
【7月更文挑战第25天】 ERP系统中的绩效管理与考核
688 2
7-10|could not find expected ':' in "/data/csjs/docker-compose.yml", line 549, column 19
7-10|could not find expected ':' in "/data/csjs/docker-compose.yml", line 549, column 19
|
XML Java 数据格式
@Configuration的作用
@Configuration的作用
511 1
|
算法 安全 前端开发
Java Queue接口及其常用实现类分析
Java Queue接口及其常用实现类分析
789 2