struts2实现文件上传(类型、大小过滤——手动、拦截器)

struts2实现文件上传(类型、大小过滤——手动、拦截器)

1、首先需要引入上传文件所需的jar包,下面是对应的maven坐标。
<!-- 文件上传 -->
		<dependency>
			<groupId>commons-fileupload</groupId>
			<artifactId>commons-fileupload</artifactId>
			<version>1.3.1</version>
		</dependency>
		<dependency>
			<groupId>commons-io</groupId>
			<artifactId>commons-io</artifactId>
			<version>2.4</version>
		</dependency>

2、添加jsp文件aaa.jsp、bbb.jsp和ccc.jsp
aaa.jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
	String path = request.getContextPath();
	String basePath = request.getScheme() + "://"
			+ request.getServerName() + ":" + request.getServerPort()
			+ path + "/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">

<title>My JSP 'aaa.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">
	-->

</head>

<body>
	<h1>aaa.jsp</h1>
	<h1>文件上传</h1>
	<form action="up" method="post" enctype="multipart/form-data">
		file: <input
			type="file" name="file"><br> <input type="submit"
			value="提交">
	</form>
</body>
</html>
bbb.jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
	String path = request.getContextPath();
	String basePath = request.getScheme() + "://"
			+ request.getServerName() + ":" + request.getServerPort()
			+ path + "/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">

<title>My JSP 'aaa.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">
	-->

</head>

<body>
	<h1>上传成功!!!</h1>
</body>
</html>
ccc.jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
	String path = request.getContextPath();
	String basePath = request.getScheme() + "://"
			+ request.getServerName() + ":" + request.getServerPort()
			+ path + "/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">

<title>My JSP 'aaa.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">
	-->

</head>

<body>
	<h1>上传失败!!!</h1>
</body>
</html>
3、编写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" />
    <!-- 指定允许上传的文件最大字节数。默认值是2097152(2M) -->
    <constant name="struts.multipart.maxSize" value="62914560"/>
    
	<package name="xueyoupackage" namespace="/" extends="struts-default">
		<action name="aaa">
			<result>/WEB-INF/content/aaa.jsp</result>
		</action>
		<action name="up" class="com.xueyoucto.random.FileUploadAction">
			<result name="success">/WEB-INF/content/bbb.jsp</result>
			<result name="error">/WEB-INF/content/ccc.jsp</result>
		</action>
	</package>
</struts>  
4、编写action类
package com.xueyoucto.random;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.UUID;
import java.util.regex.Pattern;

import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.ActionSupport;

public class FileUploadAction extends ActionSupport {

	/** 
	 *  
	 */
	private static final long serialVersionUID = 2709198903287378619L;

	private File file;
	private String fileFileName;
	private String fileContentType;

	public File getFile() {
		return file;
	}

	public void setFile(File file) {
		this.file = file;
	}

	public String getFileFileName() {
		return fileFileName;
	}

	public void setFileFileName(String fileFileName) {
		this.fileFileName = fileFileName;
	}

	public String getFileContentType() {
		return fileContentType;
	}

	public void setFileContentType(String fileContentType) {
		this.fileContentType = fileContentType;
	}

	public String execute() throws Exception{  
        String randomFilename = UUID.randomUUID().toString();  
        String root = ServletActionContext.getServletContext().getRealPath("/test");  
        System.out.println("root: " + root);  
        System.out.println("fileFileName : " + fileFileName);  
        System.out.println("fileContentType:" + fileContentType);  
          
        String ex = Pattern.compile("^.*\\.(.*)$").matcher(fileFileName).replaceAll(".$1");  
        System.out.println(ex);  
        String path = "d:/123/" + randomFilename + ex;
        FileOutputStream fos = new FileOutputStream(new File(path));  
        FileInputStream fis = new FileInputStream(file);  
        int len = 0;  
        byte[] buffer =  new byte[1024];  
        int maxSize = 0;  
        while(((len = fis.read(buffer))>0) &&(maxSize<5)){  
            fos.write(buffer,0,len);  
            maxSize++;  
        }  
        fos.close();  
        fis.close();  
        System.out.println(maxSize+"===========");  
        System.out.println(file.length());
        if(maxSize < 5){  
            return ActionSupport.SUCCESS;  
        }  
        else{  
        	File deltempFile = new File(path);
        	if(deltempFile.isFile()){
        		deltempFile.delete();
        	}
            return ActionSupport.ERROR;  
        }  
    }

}



5、运行结果

选择文件

点击提交

输出的内容:

6、如果上传文件过大,那么会跳转到失败的界面上

10、输入内容

补充一下,后来才知道有一个属性可以直接得到上传文件的大小file.length(),可以直接通过这个属性过滤文件的大小。


11、除了上面手动的方式进行判断文件类型和扩展名以及大小之外,还有一种方法,就是使用struts2的拦截器。
<?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" />  
    <!-- 指定允许上传的文件最大字节数。默认值是2097152(2M) -->  
    <constant name="struts.multipart.maxSize" value="62914560"/>  
    <constant name="struts.custom.i18n.resources" value="com.xueyoucto.random.fileuploadmessage"></constant>
    
    <package name="xueyoupackage" namespace="/" extends="struts-default">  
        <action name="aa">  
            <result>/WEB-INF/content/aaa.jsp</result>  
        </action>   
        <action name="up" class="com.xueyoucto.random.FileUploadAction">  
        	<interceptor-ref name="fileUpload">
        		<param name="allowedTypes">image/png,image/gif,image/jpeg</param>
        		<param name="allowedExtensions">png,gif,jpeg</param>
        		<param name="maximumSize">9000</param>
        	</interceptor-ref>
        	<!-- 系统默认拦截器 -->
        	<interceptor-ref name="defaultStack"></interceptor-ref>
            <result name="success">/WEB-INF/content/bbb.jsp</result>  
            <result name="error">/WEB-INF/content/ccc.jsp</result>  
            <result name="input">/WEB-INF/content/aaa.jsp</result>  
        </action>        
    </package>  
</struts>  

注意,配置拦截器后,需要在返回结果中出现input类型的result。因为如果上传失败,struts2会自动跳转到input类型的结果中。
12、在aaa.jsp中增加错误提示信息
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
   <%@taglib uri="/struts-tags" prefix="s"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>aaa.jsp</title>
</head>
<body>
<h1>aaa.jsp</h1>
<h1>文件上传</h1>  
    <form action="up" method="post" enctype="multipart/form-data">  
        file: <input  
            type="file" name="file"><br> <input type="submit"  
            value="提交">  
    </form> <br/>
    <s:fielderror/>
</body>
</html>
13、此时,如果上传的问题文件类型、文件大小、文件扩展名不符合的话,会出现英文的提示信息。这struts2自带的提示信息,在struts2-core-2.x.x.x.jar\org\apache\struts2\struts-messages.properties文件中。可以进行自定义进行修改。在com.xueyoucto.random中增加文件fileuploadmessage.properties,文件内容如下:

struts.messages.error.uploading=上传错误: {0}

struts.messages.error.file.too.large=文件太大: {0} "{1}" "{2}" {3}

struts.messages.error.content.type.not.allowed=不支持的文件类型: {0} "{1}" "{2}" {3}

struts.messages.error.file.extension.not.allowed=不支持的文件扩展名: {0} "{1}" "{2}" {3}

(此处参考:http://blog.csdn.net/yeshanghai_c/article/details/9618633《struts2--文件上传和uploadFile拦截器》)

14、运行截图





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值