struts2文件上传

FileUpload.java:
package blog.action;
import java.io.File;
import java.io.IOException;
import org.apache.commons.io.FileUtils;
import org.apache.struts2.ServletActionContext;
public class FileUpload {
private File fileUpload;//得到上传的文件
private String fileUploadContentType;//得到文件的类型
private String fileUploadFileName;//得到文件的名称
private String msg;
public File getFileUpload() {
return fileUpload;
}
public void setFileUpload(File fileUpload) {
this.fileUpload = fileUpload;
}
public String getFileUploadContentType() {
return fileUploadContentType;
}
public void setFileUploadContentType(String fileUploadContentType) {
this.fileUploadContentType = fileUploadContentType;
}
public String getFileUploadFileName() {
return fileUploadFileName;
}
public void setFileUploadFileName(String fileUploadFileName) {
this.fileUploadFileName = fileUploadFileName;
}
public String getMsg() {
return msg;
}
public String upload(){
String realPath = ServletActionContext.getServletContext().getRealPath("/file");
File file = new File(realPath);
if (!file.exists()) {
file.mkdirs();
}
try {
FileUtils.copyFile(fileUpload, new File(file, fileUploadFileName));
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("上传路径:" + realPath + "\t文件类型:" + fileUploadContentType);
msg = "上传成功";
return "message";
}
public String execute(){
return "success";
}
}
fileUpload.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">
</head>
<body>
<form action="${pageContext.request.contextPath }/control/file/operation_upload.action" enctype="multipart/form-data" method="post">
<input type="file" name="fileUpload" />
<input type="submit" value="上传"/>
</form>
</body>
</html>
struts-fileUpload.xml:
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
<package name="file" extends="struts-default" namespace="/control/file">
<action name="operation_*" class="blog.action.FileUpload" method="{1}" >
<result name="message">/WEB-INF/page/message.jsp</result>
<result name="success">/WEB-INF/page/fileUpload.jsp</result>
</action>
</package>
</struts>
struts.xml:
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
<constant name="struts.multipart.maxSize" value="30000000"></constant>
<!-- 上传文件的大小限制 -->
<include file="struts-fileUpload.xml"></include>
</struts>