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%>">
</head>
<body>
<form action="upfile.action" method="post" enctype="multipart/form-data">
<input type="file" name="myFile">
<input type="submit" value="提 交">
</form>>
</body>
</html>
文件上传的action
package com.action;
import java.io.File;
import java.io.IOException;
import org.apache.commons.io.FileUtils;
import org.apache.struts2.ServletActionContext;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
public class UpFile extends ActionSupport {
private File myFile;
private String myFileFileName;
private String myFileContentType;
ActionContext actionContext = ActionContext.getContext();
public String upfile() {
System.out.println(myFileFileName);
/*
* 获取upload
* 文件夹在磁盘上的绝对路径>>”H:/apache-tomcat-8.0.52/webapps/struts2/upload“
*/
//开始的时候,上传文件可以成功,但是上传的文件要么找不到放在那里、要么是tmp结尾的临时文件,后来将path改成如下代码,成功解决了这个问题
String path = ServletActionContext.getServletContext().getRealPath("/upload");
System.out.println(path);
File file = new File(path);
if (file.exists())
file.mkdirs();
try {
// 工具类拷贝文件
FileUtils.copyFile(myFile, new File(file, myFileFileName));
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("上传结束……");
return "success";
}
public File getMyFile() {
return myFile;
}
public void setMyFile(File myFile) {
this.myFile = myFile;
}
public String getMyFileFileName() {
return myFileFileName;
}
public void setMyFileFileName(String myFileFileName) {
this.myFileFileName = myFileFileName;
}
public String getMyFileContentType() {
return myFileContentType;
}
public void setMyFileContentType(String myFileContentType) {
this.myFileContentType = myFileContentType;
}
}
struts.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="user" extends="struts-default">
<interceptors >
<action name="upfile" class="com.action.UpFile" method="upfile">
文件上传拦截器,可以设置文件大小的参数
<interceptor-ref name="fileUpload" >
<param name="maxmmSize">1024000</param>
</interceptor-ref>
启用默认的拦截器栈
<interceptor-ref name="defaultStack" />
<result name="success" >/upsuccess.jsp</result>
<result name="error">/500.jsp</result>
</action>
</package>
</struts>