Struts2框架单文件上传*
- 先引入struts的核心依赖
<!-- https://mvnrepository.com/artifact/org.apache.struts/struts2-core -->
<dependency>
<groupId>org.apache.struts</groupId>
<artifactId>struts2-core</artifactId>
<version>2.3.35</version>
</dependency>
- 在web.xml中配置核心过滤器
<filter>
<filter-name>struts2</filter-name>
<filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>*.action</url-pattern>
</filter-mapping>
- 在创建index.jsp页面
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!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>Insert title here</title>
</head>
<body>
<form action="uploadAction_upload.action" method="post" enctype="multipart/form-data">
<input type="file" name="picture">
<input type="submit" value="上传">
</form>
</body>
</html>
注意文件上传的时候 表单的提交方式一定要是post
指定表单的提交类型 :multipart/form-data
- 在新建一个UploadAction的java类并继承 ActionSupp
public class UploadAction extends ActionSupport{
private File picture;//jsp页面上的文件选择框的name必须要一致
private String pictureFileName;//xxxFileName xxx代表页面上的文件选择框的name
HttpServletRequest request;
//单文件上传的action
public String upload() {
//将上传的文件保存
try {
//获取当前项目所在服务器的路径
request=ServletActionContext.getRequest();
//获取项目的真实路径
String path=request.getRealPath("/images");
String extName=pictureFileName.substring(pictureFileName.lastIndexOf('.'));
//给图片设置名字按时间设置以防重名
SimpleDateFormat sdf=new SimpleDateFormat("yyyyMMddHHmmssSSSS");
String fileName=sdf.format(new Date());
//通过保存文件的路径和文件名称创建文件对象
File f=new File(path+"/"+fileName+extName);
//使用文件帮助类的复制文件的方法
FileUtils.copyFile(picture, f);
} catch (Exception e) {
e.printStackTrace();
}
return SUCCESS;
}
public String getPictureFileName() {
return pictureFileName;
}
public void setPictureFileName(String pictureFileName) {
this.pictureFileName = pictureFileName;
}
public File getPicture() {
return picture;
}
public void setPicture(File picture) {
this.picture = picture;
}
}
- 创建struts.xml文件 写入约束
"-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
"http://struts.apache.org/dtds/struts-2.3.dtd">
<struts>
<package name="default" namespace="/" extends="struts-default">
<action name="uploadAction_*" class="com.lx.action.UploadAction" method="{1}">
<result>index.jsp</result>
</action>
</package>
</struts>