转自: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>

 

struts2文件上传类型的过滤的更多相关文章

  1. struts2文件上传,文件类型 allowedTypes

    struts2文件上传,文件类型 allowedTypes 1 '.a' : 'application/octet-stream', 2 '.ai' : 'application/postscript ...

  2. Struts2文件上传和下载(原理)

    转自:http://zhou568xiao.iteye.com/blog/220732 1.    文件上传的原理:表单元素的enctype属性指定的是表单数据的编码方式,该属性有3个值:1)     ...

  3. 【Java EE 学习 35 下】【struts2】【struts2文件上传】【struts2自定义拦截器】【struts2手动验证】

    一.struts2文件上传 1.上传文件的时候要求必须使得表单的enctype属性设置为multipart/form-data,把它的method属性设置为post 2.上传单个文件的时候需要在Act ...

  4. springMvc 使用ajax上传文件,返回获取的文件数据 附Struts2文件上传

    总结一下 springMvc使用ajax文件上传 首先说明一下,以下代码所解决的问题 :前端通过input file 标签获取文件,通过ajax与后端交互,后端获取文件,读取excel文件内容,返回e ...

  5. Struts2文件上传下载

    Struts2文件上传 Struts2提供 FileUpload拦截器,用于解析 multipart/form-data 编码格式请求,解析上传文件的内容,fileUpload拦截器 默认在defau ...

  6. Struts2 文件上传

    一:表单准备 ① 要想使用HTML 表单上传一个或多个文件     –须把 HTML表单的 enctype属性设置为multipart/form-data     –须把HTML 表单的method ...

  7. Struts2文件上传方式与上传失败解决方式

    首先将几个对象弄出来第一个 上传页面第二个 上传action第三个 startut2配置文件 我的文字描述不是很好,但是终归是自己写出来的,后来我在网上看到一篇关于文件上传描述的非常清楚的文章, 链接 ...

  8. JAVA Web 之 struts2文件上传下载演示(一)(转)

    JAVA Web 之 struts2文件上传下载演示(一) 一.文件上传演示 1.需要的jar包 大多数的jar包都是struts里面的,大家把jar包直接复制到WebContent/WEB-INF/ ...

  9. (八)Struts2 文件上传和下载

    所有的学习我们必须先搭建好Struts2的环境(1.导入对应的jar包,2.web.xml,3.struts.xml) 第一节:Struts2 文件上传 Struts2 文件上传基于Struts2 拦 ...

随机推荐

  1. C语言代码优化(转)

    .选择合适的算法和数据结构 选择一种合适的数据结构很重要,如果在一堆随机存放的数中使用了大量的插入和删除指令,那使用链表要快得多.数组与指针语句具有十分密切的关系,一般来说,指针比较灵活简洁,而数组则 ...

  2. Java并发编程笔记—基础知识—实用案例

    如何正确停止一个线程 1)共享变量的使用 中断线程最好的,最受推荐的方式是,使用共享变量(shared variable)发出信号,告诉线程必须停止正在运行的任务.线程必须周期性的核查这一变量(尤其在 ...

  3. 为dedecms文章列表页标题增加序号,第二页开始才显示第x页

    想必大伙建站都会写文章,随着时间的推移,你的智慧结晶会越来越多,一般的建站程序早帮你想好了,把这些文章做成一个列表,比如dedecms栏目列表,便于观众浏览,但有个问题就是dedecms文章列表页标题 ...

  4. CloudPlatform和CloudStack的关系

    The Scalr team is at the CloudStack Collab Conf, and this post summarizes a few things we learned. C ...

  5. IIS计数器

    Bytes Total/sec 是 Bytes Sent/sec 与 Bytes Received/sec 的总和.这是 Web 服务每秒传输的总字节数. Cache Total Turnover R ...

  6. php面试题之四——PHP面向对象(基础部分)

    四.PHP面向对象 1. 写出 php 的 public.protected.private 三种访问控制模式的区别(新浪网技术部) public:公有,任何地方都可以访问 protected:继承, ...

  7. HDU 1029 Ignatius and the Princess IV

    解题报告: 题目大意:就是要求输入的N个数里面出现的次数最多的数是哪一个,水题.暴力可过,定义一个一位数组,先用memset函数初始化,然后每次输入一个数就将下标对应的上标对应的那个数加一,最后将整个 ...

  8. Nginx+tomcat负载均衡配置

    Nginx+tomcat是目前主流的java web架构,如何让nginx+tomcat同时工作呢,也可以说如何使用nginx来反向代理tomcat后端均衡呢?直接安装配置如下: 1.JAVA JDK ...

  9. CentOS 关闭蜂鸣器声音

    也许你会遇到像我这样的情况,每次使用Linux终端,当听到发出“嘀嘀”的声音时候,我都有种把我的机箱拆掉把那个内置的蜂鸣装置拽下来的冲动.按 Tab时候“嘀嘀”,按空格时候“嘀嘀”,每个在vi中错误的 ...

  10. Ubuntu系统如何查看硬件配置信息

    查看ubuntu硬件信息 1, 主板信息 .查看主板的序列号 -------------------------------------------------- #使用命令 dmidecode | ...