struts2实现文件过滤

一、手动实现文件过滤

1.uploadAction.java

 

//文件过滤属性,通过struts.xml文件配置allowtypes属性值
	private String allowtypes;
	
	
	public String getAllowtypes() {
		return allowtypes;
	}


	public void setAllowtypes(String allowtypes) {
		this.allowtypes = allowtypes;
	}

比较当前上传文件的格式和允许上传文件格式

//过滤文件

	public String filetypes(){
		
		String filetype=getUploadContentType();
		String[] types=getAllowtypes().split(",");
		for(String type:types){
			if(type.equals(filetype)){
				return "ok";
			}
		}
		return "error";
	}
	
	@Override
	public String execute() throws Exception {

		if(filetypes().equals("error")){
			this.addFieldError("uploadfileerror", "上传文件类型错误");
			return "error";
		}


 

2.struts.xml(在struts配置文件中allowTypes的属性值)

 

<struts>

    <constant name="struts.enable.DynamicMethodInvocation" value="false" />
    <constant name="struts.devMode" value="true" />
	<constant name="struts.i18n.encoding" value="utf-8"/>
    <package name="parameter" namespace="/" extends="struts-default">

        <action name="upload1" class="com.ru.action.UploadAction">
        	<param name="savepath">/upload</param>
        	<!-- 文件上传格式 -->
        	<param name="allowtypes">image/gif,image/x-png,image/jpg,image/jpeg,application/vnd.openxmlformats-officedocument.wordprocessingml.document</param>
            <result name="sucess">/WEB-INF/jsp/sucess.jsp</result>
            <result name="error">/WEB-INF/jsp/error.jsp</result>
        </action>      
    </package>
</struts>

二、struts2提供的过滤机制

struts.xml

 

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
	"-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
	"http://struts.apache.org/dtds/struts-2.3.dtd">

<struts>

    <constant name="struts.enable.DynamicMethodInvocation" value="false" />
    <constant name="struts.devMode" value="true" />
	<constant name="struts.i18n.encoding" value="utf-8"/>
    <package name="parameter" namespace="/" extends="struts-default">

        <action name="upload1" class="com.ru.action.UploadAction">
        	<param name="savepath">/upload</param>
        	
        	
        	
        	
        	<!-- Struts2提供的文件上传拦截器-->
        	<interceptor-ref name="fileUpload">
        	<!-- 允许上传的文件格式 -->
        		<param name="allowedTypes">image/gif,image/x-png,image/jpg,image/jpeg,application/vnd.openxmlformats-officedocument.wordprocessingml.document</param>
        	<!-- 附件大小 -->	
        		<param name="maximumSize">2000000</param>
        	</interceptor-ref>
        	<!-- 默认拦截器 -->
        	<interceptor-ref name="defaultStack"></interceptor-ref>
        	<!-- 配置struts2的默认视图文件必须是"input" -->
        	<result name="input">/WEB-INF/jsp/error.jsp</result>
        	
        	
        	
        	
            <result name="sucess">/WEB-INF/jsp/sucess.jsp</result>
            
        </action>      
    </package>
</struts>


你可能感兴趣的:(struts2)