struts2实现文件上传功能(FileUtils类的copyFile方法实现)

//action类代码
package com.rocky.uploadaction;

import java.io.File;

import org.apache.commons.io.FileUtils;
import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;

public class ImageAction extends ActionSupport {
	public File fileN;
	public String fileNFileName;

	public File getFileN() {
		return fileN;
	}

	public void setFileN(File fileN) {
		this.fileN = fileN;
	}

	public String getFileNFileName() {
		return fileNFileName;
	}

	public void setFileNFileName(String fileNFileName) {
		this.fileNFileName = fileNFileName;
	}

	public String excute() throws Exception {
		if (fileN != null) {
			String save = ServletActionContext.getServletContext().getRealPath(
					"/images");
			File f = new File(save);
			if (!f.exists())
				f.mkdirs();
			FileUtils.copyFile(fileN, new File(f, fileNFileName));
			ActionContext.getContext().put("message", "文件上传成功!");
		}
		return "success";
	}

}
//struts2.xml配置文件代码,
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.1//EN" "http://struts.apache.org/dtds/struts-2.1.dtd">
<struts>
	<package name="test" extends="struts-default">
		<action name="fl" class="com.rocky.uploadaction.ImageAction"
			method="excute">
			<result name="success">/index.jsp</result>
			<result name="input">/index.jsp</result>
		</action>
	</package>

</struts>    
//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 'FileUpload.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">
	</head>
	<body>
		
<form enctype="multipart/form-data" action="fl.action" method="post">
	<input type="file" name="fileN" />
	<input type="submit" value="确定上传">
</form>
</body>
</html>

  

posted @ 2013-01-29 16:37  chenxiaofeng  阅读(1448)  评论(0编辑  收藏  举报