struts2文件上传类型的过滤
转自: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 | packageaction;importjava.io.File;importjava.io.FileInputStream;importjava.io.FileOutputStream;importorg.apache.struts2.ServletActionContext;importcom.opensymphony.xwork2.ActionSupport;publicclassUploadAction extendsActionSupport {    /**     *      */    privatestaticfinallongserialVersionUID = 1L;    privateString title;    privateFile uploadfile;    privateString uploadfileContentType;    privateString uploadfileFileName;    privateString savePath;    privateString allowType;//定义该Action允许上传的文件类型        publicbooleancheck(String type){        String[] types=allowType.split(",");        for(String s:types){            if(s.equals(type)){                returntrue;            }        }        returnfalse;            }    publicvoidvalidate(){        booleanb=check(uploadfileContentType);        if(!b){            addFieldError("upload","上传文件错误");        }    }    publicString getAllowType() {        returnallowType;    }    publicvoidsetAllowType(String allowType) {        this.allowType = allowType;    }    publicString upload()  throwsException {                        FileInputStream fis = newFileInputStream(getUploadfile());        FileOutputStream  fos=newFileOutputStream(getSavePath()+"\\"+getUploadfileFileName());        byte[] buffer=newbyte[1024];        intlen=0;        while((len=fis.read(buffer))>0){            fos.write(buffer,0,len);        }        fos.close();        fis.close();                returnSUCCESS;    }    publicString getTitle() {        returntitle;    }    publicvoidsetTitle(String title) {        this.title = title;    }    publicFile getUploadfile() {        returnuploadfile;    }    publicvoidsetUploadfile(File uploadfile) {        this.uploadfile = uploadfile;    }    publicString getUploadfileContentType() {        returnuploadfileContentType;    }    publicvoidsetUploadfileContentType(String uploadfileContentType) {        this.uploadfileContentType = uploadfileContentType;    }    publicString getUploadfileFileName() {        returnuploadfileFileName;    }    publicvoidsetUploadfileFileName(String uploadfileFileName) {        this.uploadfileFileName = uploadfileFileName;    }    publicString getSavePath() {        returnServletActionContext.getServletContext().getRealPath(savePath);//得到绝对路径    }    publicvoidsetSavePath(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>    <packagename="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"%><%@taglibprefix="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"%><%@taglibprefix="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 | packageaction;importjava.io.File;importjava.io.FileInputStream;importjava.io.FileOutputStream;importorg.apache.struts2.ServletActionContext;importcom.opensymphony.xwork2.ActionSupport;publicclassUploadAction extendsActionSupport {    /**     *      */    privatestaticfinallongserialVersionUID = 1L;    privateString title;    privateFile uploadfile;    privateString uploadfileContentType;    privateString uploadfileFileName;    privateString savePath;    privateString allowedTypes;                publicString getAllowedTypes() {        returnallowedTypes;    }    publicvoidsetAllowedTypes(String allowedTypes) {        this.allowedTypes = allowedTypes;    }    publicString upload()  throwsException {                        FileInputStream fis = newFileInputStream(getUploadfile());        FileOutputStream  fos=newFileOutputStream(getSavePath()+"\\"+getUploadfileFileName());        byte[] buffer=newbyte[1024];        intlen=0;        while((len=fis.read(buffer))>0){            fos.write(buffer,0,len);        }        fos.close();        fis.close();                returnSUCCESS;    }    publicString getTitle() {        returntitle;    }    publicvoidsetTitle(String title) {        this.title = title;    }    publicFile getUploadfile() {        returnuploadfile;    }    publicvoidsetUploadfile(File uploadfile) {        this.uploadfile = uploadfile;    }    publicString getUploadfileContentType() {        returnuploadfileContentType;    }    publicvoidsetUploadfileContentType(String uploadfileContentType) {        this.uploadfileContentType = uploadfileContentType;    }    publicString getUploadfileFileName() {        returnuploadfileFileName;    }    publicvoidsetUploadfileFileName(String uploadfileFileName) {        this.uploadfileFileName = uploadfileFileName;    }    publicString getSavePath() {        returnServletActionContext.getServletContext().getRealPath(savePath);//得到绝对路径    }    publicvoidsetSavePath(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>    <packagename="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文件上传类型的过滤的更多相关文章
- struts2文件上传,文件类型 allowedTypes
		struts2文件上传,文件类型 allowedTypes 1 '.a' : 'application/octet-stream', 2 '.ai' : 'application/postscript ... 
- Struts2文件上传和下载(原理)
		转自:http://zhou568xiao.iteye.com/blog/220732 1. 文件上传的原理:表单元素的enctype属性指定的是表单数据的编码方式,该属性有3个值:1) ... 
- 【Java EE 学习 35 下】【struts2】【struts2文件上传】【struts2自定义拦截器】【struts2手动验证】
		一.struts2文件上传 1.上传文件的时候要求必须使得表单的enctype属性设置为multipart/form-data,把它的method属性设置为post 2.上传单个文件的时候需要在Act ... 
- springMvc 使用ajax上传文件,返回获取的文件数据 附Struts2文件上传
		总结一下 springMvc使用ajax文件上传 首先说明一下,以下代码所解决的问题 :前端通过input file 标签获取文件,通过ajax与后端交互,后端获取文件,读取excel文件内容,返回e ... 
- Struts2文件上传下载
		Struts2文件上传 Struts2提供 FileUpload拦截器,用于解析 multipart/form-data 编码格式请求,解析上传文件的内容,fileUpload拦截器 默认在defau ... 
- Struts2 文件上传
		一:表单准备 ① 要想使用HTML 表单上传一个或多个文件 –须把 HTML表单的 enctype属性设置为multipart/form-data –须把HTML 表单的method ... 
- Struts2文件上传方式与上传失败解决方式
		首先将几个对象弄出来第一个 上传页面第二个 上传action第三个 startut2配置文件 我的文字描述不是很好,但是终归是自己写出来的,后来我在网上看到一篇关于文件上传描述的非常清楚的文章, 链接 ... 
- JAVA Web 之 struts2文件上传下载演示(一)(转)
		JAVA Web 之 struts2文件上传下载演示(一) 一.文件上传演示 1.需要的jar包 大多数的jar包都是struts里面的,大家把jar包直接复制到WebContent/WEB-INF/ ... 
- (八)Struts2 文件上传和下载
		所有的学习我们必须先搭建好Struts2的环境(1.导入对应的jar包,2.web.xml,3.struts.xml) 第一节:Struts2 文件上传 Struts2 文件上传基于Struts2 拦 ... 
随机推荐
- mysql-binlog日志恢复数据库
			binlog日志用于记录所有更新了数据或者已经潜在更新了数据的所有语句.语句以“事件”的形式保存,它描述数据更改.当我们因为某种原因导致数据库出现故障时,就可以利用binlog日志来挽回(前提是已经配 ... 
- SVN服务器搭建--Subversio与TortoiseSVN的配置安装
			SVN服务器搭建和使用(一) Subversion是优秀的版本控制工具,其具体的的优点和详细介绍,这里就不再多说. 首先来下载和搭建SVN服务器. 现在Subversion已经迁移到apache网站上 ... 
- 移动端Web开发注意点
			不用考虑浏览器兼容性 移动端开发主要对象是手持设备,其中绝大部分是IOS和Android系统,so,在开发此类页面时不必纠结IE和其他一些2B浏览器的兼容性,webkit是本次开发重点. 当然,不同版 ... 
- hdu.5202.Rikka with string(贪心)
			Rikka with string Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/65536 K (Java/Others ... 
- cocos基础教程(4)基础概念介绍
			在Cocos2d-x-3.x引擎中,采用节点树形结构来管理游戏对象,一个游戏可以划分为不同的场景,一个场景又可以分为不同的层,一个层又可以拥有任意个可见的游戏节点(即对象,游戏中基本上所有的类都派生于 ... 
- 第3章 K近邻法
			参考: http://www.cnblogs.com/juefan/p/3807713.html http://blog.csdn.net/v_july_v/article/details/82036 ... 
- 为win7添加ubuntu的启动引导项
			利用MBRFix删除ubuntu的开机引导界面,恢复成win7引导之后,为win7添加ubuntu的启动引导项: 直接利用EasyBCD添加一个Grub2的引导项即可 参考:http://mathis ... 
- shell 生成指定范围随机数与随机字符串   .
			shell 生成指定范围随机数与随机字符串 分类: shell 2014-04-22 22:17 20902人阅读 评 ... 
- Android中获取IMSI和IMEI
			TelephonyManager mTelephonyMgr = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE); Str ... 
- Kmin
			Kmin of Array [本文链接] http://www.cnblogs.com/hellogiser/p/kmin-of-array.html [代码] C++ Code 12345678 ... 
