struts版本为struts-2.1.8.1
项目名为 struts2
从路径 struts-2.1.8.1\lib 下将 struts2-core-2.1.8.1.jar,xwork-core-2.1.6.jar,commons-fileupload-1.2.1.jar,commons-io-1.3.2.jar 复制到 WEB-INF/lib 目录下
配置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.action.extension" value="do,action"></constant> <!-- 设置文件上传大小限制10M --> <constant name="struts.multipart.maxSize" value="10701096"></constant> <package name="fileupload" namespace="/fileupload" extends="struts-default"> <action name="upload" class="com.cool.fileupload.FileUploadAction" method="execute"> <result name="success">/WEB-INF/page/message.jsp</result> </action> </package> </struts>
创建第一个页面 fileupload.jsp (用于上传文件)
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>Fileupload 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}/fileupload/upload.action" enctype="multipart/form-data" method="post">
文件:<input type="file" name="image" />
<input type="submit" value="上传"/>
</form>
</body>
</html>
创建第二个页面 /page/message.jsp (用于显示返回信息)
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>Message 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>
${message }
</body>
</html>
创建处理文件上传的Action
package com.cool.fileupload;
import java.io.File;
import org.apache.commons.io.FileUtils;
import org.apache.struts2.ServletActionContext;
import com.opensymphony.xwork2.ActionContext;
public class FileUploadAction {
private File image;
private String imageFileName;
public File getImage() {
return image;
}
public void setImage(File image) {
this.image = image;
}
public String getImageFileName() {
return imageFileName;
}
public void setImageFileName(String imageFileName) {
this.imageFileName = imageFileName;
}
public String execute() throws Exception{
String realPath = ServletActionContext.getServletContext().getRealPath("/image");
if(this.image!=null){
File saveFile = new File(new File(realPath), this.imageFileName);
if(!saveFile.getParentFile().exists()) saveFile.getParentFile().mkdirs();
FileUtils.copyFile(image, saveFile);
}
ActionContext.getContext().put("message","上传成功");
return "success";
}
}
访问路径为 http://localhost:8080/struts2/fileupload.jsp (struts2为项目名)
选择文件,然后单击上传按钮,画面跳转到 /page/message.jsp,显示【上传成功】
然后到发布路径下看文件是否真正上传 F:\Tomcat\webapps\struts2\image ( F:\Tomcat 为本机Tomcat路径 )
测试成功。
关于多文件上传如下,只需将image和imageFileName定义成数组型即可
private File[] image;
private String[] imageFileName;
以上