转自:http://www.2cto.com/kf/201403/282787.html

第一种解决方案:

1.手动实现文件过滤:

判断上传的文件是否在允许的范围内
定义该Action允许上传的文件类型 private String allowTypes;
利用Struts2的输入效验判断用户的输入的文件是否合理

UploadAction.java

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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
package action;
 
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
 
import org.apache.struts2.ServletActionContext;
 
import com.opensymphony.xwork2.ActionSupport;
 
public class UploadAction extends ActionSupport {
    /**
     *
     */
    private static final long serialVersionUID = 1L;
    private String title;
    private File uploadfile;
    private String uploadfileContentType;
    private String uploadfileFileName;
    private String savePath;
    private String allowType;//定义该Action允许上传的文件类型
     
    public boolean check(String type){
        String[] types=allowType.split(",");
        for(String s:types){
            if(s.equals(type)){
                return true;
            }
        }
        return false;
         
    }
    public void  validate(){
        boolean b=check(uploadfileContentType);
        if(!b){
            addFieldError("upload","上传文件错误");
        }
    }
    public String getAllowType() {
        return allowType;
    }
 
    public void setAllowType(String allowType) {
        this.allowType = allowType;
    }
 
    public String upload()  throws  Exception {
         
         
        FileInputStream fis = new FileInputStream(getUploadfile());
        FileOutputStream  fos=new FileOutputStream(getSavePath()+"\\"+getUploadfileFileName());
        byte[] buffer=new byte[1024];
        int len=0;
        while((len=fis.read(buffer))>0){
            fos.write(buffer,0,len);
        }
        fos.close();
        fis.close();
         
        return SUCCESS;
    }
 
    public String getTitle() {
        return title;
    }
 
    public void setTitle(String title) {
        this.title = title;
    }
 
 
    public File getUploadfile() {
        return uploadfile;
    }
 
    public void setUploadfile(File uploadfile) {
        this.uploadfile = uploadfile;
    }
 
    public String getUploadfileContentType() {
        return uploadfileContentType;
    }
 
    public void setUploadfileContentType(String uploadfileContentType) {
        this.uploadfileContentType = uploadfileContentType;
    }
 
    public String getUploadfileFileName() {
        return uploadfileFileName;
    }
 
    public void setUploadfileFileName(String uploadfileFileName) {
        this.uploadfileFileName = uploadfileFileName;
    }
 
    public String getSavePath() {
        return ServletActionContext.getServletContext().getRealPath(savePath);//得到绝对路径
    }
 
    public void setSavePath(String savePath) {
        this.savePath = savePath;
    }
 
}

struts.xml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
<!--?xml version="1.0" encoding="UTF-8"?-->
 
<struts>
 
    <package name="hello" namespace="/hello" extends="struts-default">
         
            <!-- 设置允许上传的文件类型 -->
                <param name="allowType">image/x-png,file/txt,image/jpeg
             
            <param name="savePath">/uploadFiles
            <result name="success">
                /success.jsp
            </result>
            <result name="input">
                /index.jsp
            </result>
        </action>
    </package>
</struts>

index.jsp

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
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@taglib  prefix="s"  uri="/struts-tags"%>>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
 
 
<html>
   
     
    <title>My JSP 'index.jsp' starting page</title>
    <meta http-equiv="pragma" content="no-cache">
    <meta http-equiv="cache-control" content="no-cache">
    <meta http-equiv="expires" content="0">   
    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
    <meta http-equiv="description" content="This is my page">
    <!--
    <link rel="stylesheet" type="text/css" href="styles.css">
    -->
   
   
   
  <s:fielderror>
    <form action="/Upload-1/hello/login" method="post" enctype="multipart/form-data">
    文件名:<input type="text" name="title">
    文件:<input type="file" name="uploadfile">
<input type="submit">
    </form>
   
 
</s:fielderror>

success.jsp

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@taglib  prefix="s" uri="/struts-tags"%>
 
   
   
  <%
String path = request.getContextPath();
  System.out.println(path);
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
System.out.println(basePath);
%>
   
  上传成功!<br>
  文件标题:<s:property value="title"><br>
  文件为:<img src="" 'uploadfiles="" '+uploadfilefilename"="" style="display: none;"><img alt="加载中..." title="图片加载中..." src="http://www.2cto.com/statics/images/s_nopic.gif">"/><br>
   
 
</s:property>

第二种解决方案:

2.拦截器实现文件过滤:

配置fileUpload拦截器两个参数:
allowedTypes:允许上传文件的类型,多个值用,分开
maximumSize:允许上传文件的大小,单位字节。

UploadAction.java

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
package action;
 
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
 
import org.apache.struts2.ServletActionContext;
 
import com.opensymphony.xwork2.ActionSupport;
 
public class UploadAction extends ActionSupport {
    /**
     *
     */
    private static final long serialVersionUID = 1L;
    private String title;
    private File uploadfile;
    private String uploadfileContentType;
    private String uploadfileFileName;
    private String savePath;
    private String allowedTypes;
     
     
        public String getAllowedTypes() {
        return allowedTypes;
    }
    public void setAllowedTypes(String allowedTypes) {
        this.allowedTypes = allowedTypes;
    }
 
    public String upload()  throws  Exception {
         
         
        FileInputStream fis = new FileInputStream(getUploadfile());
        FileOutputStream  fos=new FileOutputStream(getSavePath()+"\\"+getUploadfileFileName());
        byte[] buffer=new byte[1024];
        int len=0;
        while((len=fis.read(buffer))>0){
            fos.write(buffer,0,len);
        }
        fos.close();
        fis.close();
         
        return SUCCESS;
    }
 
    public String getTitle() {
        return title;
    }
 
    public void setTitle(String title) {
        this.title = title;
    }
 
 
    public File getUploadfile() {
        return uploadfile;
    }
 
    public void setUploadfile(File uploadfile) {
        this.uploadfile = uploadfile;
    }
 
    public String getUploadfileContentType() {
        return uploadfileContentType;
    }
 
    public void setUploadfileContentType(String uploadfileContentType) {
        this.uploadfileContentType = uploadfileContentType;
    }
 
    public String getUploadfileFileName() {
        return uploadfileFileName;
    }
 
    public void setUploadfileFileName(String uploadfileFileName) {
        this.uploadfileFileName = uploadfileFileName;
    }
 
    public String getSavePath() {
        return ServletActionContext.getServletContext().getRealPath(savePath);//得到绝对路径
    }
 
    public void setSavePath(String savePath) {
        this.savePath = savePath;
    }
 
}

struts.xml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
<!--?xml version="1.0" encoding="UTF-8"?-->
 
<struts>
 
    <package name="hello" namespace="/hello" extends="struts-default">
         
             
             <interceptor-ref name="fileUpload">
               <param name="allowedTypes">image/x-png,image/gif,image/jpeg
               <param name="maximumSize">20000000
            </interceptor-ref>
            <interceptor-ref name="defaultStack"></interceptor-ref>
            <param name="savePath">/uploadFiles
            <result name="success">
                /success.jsp
            </result>
            <result name="input">
                /index.jsp
            </result>
        </action>
    </package>
</struts>

 

最新文章

  1. Progressive Scanning (逐行扫描) vs Interlaced Scanning (隔行扫描)
  2. quartzScheduler_Worker-1] but has failed to stop it. This is very likely to create a memory leak解决
  3. SQL Server中,Numric,Decimal,Money三种字段类型的区别
  4. SqlParameter中的size
  5. swift -- 学习记录
  6. centos6.5安装图形界面,windows远程linux图形界面
  7. CSS3中的网格
  8. Java创建线程的第二种方式:实现runable接口
  9. 关于PIL库的一些概念
  10. 【技术贴】破解Myeclipse10.7
  11. Maven tomcat插件配置和使用
  12. 在DataTable中更新、删除数据
  13. Android应用程序进程启动过程的源代码分析
  14. iOS的扩展类,扩展属性
  15. 移动端开发(四):swiper.js
  16. 重写PHP的explode办法
  17. Mysql 忘记root密码后修改root密码
  18. SoapUI简介及下载地址
  19. [Android] 基于 Linux 命令行构建 Android 应用(三):构建流程
  20. AI标尺,管理面板5.8

热门文章

  1. vim tab 和4个空格
  2. 自定义 SqlHelp
  3. springmvc 项目完整示例06 日志–log4j 参数详细解析 log4j如何配置
  4. postgresql 函数demo
  5. 每天一个linux命令day2【ss命令】
  6. 【转】基于注解的SpirngMVC简单介绍
  7. js init : function ()
  8. php-fpm启动
  9. Java for LeetCode 201 Bitwise AND of Numbers Range
  10. Extjs的radio单选框的使用