import java.io.*;
import java.util.UUID;
import com.opensymphony.xwork2.ActionContext;
import org.apache.struts2.ServletActionContext;
import com.opensymphony.xwork2.ActionSupport;
@SuppressWarnings("serial")
public class UploadAction extends ActionSupport {
private static final UUID uuid = UUID.randomUUID();
private File upload;
// 文件类型
private String uploadContentType;
// 文件名称
private String uploadFileName;
// 允许上传的类型
private String allowTypes;
// 保存路径
private String savePath;
// 接受依赖注入的方法
public void setSavePath(String savePath) {
this.savePath = savePath;
}
private String getSavePath() throws Exception {
return ServletActionContext.getServletContext().getRealPath(savePath);
// return "D:\\workspace\\3.6\\tnt\\src\\main\\webapp\\upload";
}
public void setUpload(File upload) {
this.upload = upload;
}
public void setUploadContentType(String uploadContentType) {
this.uploadContentType = uploadContentType;
}
public void setUploadFileName(String uploadFileName) {
this.uploadFileName = uploadFileName;
}
public File getUpload() {
return (this.upload);
}
public String getUploadContentType() {
return (this.uploadContentType);
}
public String getUploadFileName() {
return (this.uploadFileName);
}
public String getAllowTypes() {
return allowTypes;
}
public void setAllowTypes(String allowTypes) {
this.allowTypes = allowTypes;
}
@SuppressWarnings("static-access")
@Override
public String execute() throws Exception {
System.out.println("开始上传单个文件---");
System.out.println("保存路径=========="+getSavePath());
System.out.println("文件名称==========" + getUploadFileName());
System.out.println("文件类型==========" + getUploadContentType());
System.out.println("==========" + getUpload());
// 判断是否允许上传
String filterResult = filterType(this.getAllowTypes().split(","));
if (filterResult != null) {
ActionContext.getContext().put("typeError", "您要上传的文件类型不正确");
return filterResult;
}
// 如果文件保存路径不存在,则创建路径。
File path = new File(getSavePath(), getUploadFileName());
if (!path.exists()) {
path.getParentFile().mkdir();
}
// 重命名文件
uploadFileName = uuid.randomUUID().toString()
+ getExtention(uploadFileName);
// 以服务器的文件保存地址和原文件名建立上传文件输出流
FileOutputStream fos = new FileOutputStream(getSavePath() + "\\"
+ getUploadFileName());
FileInputStream fis = new FileInputStream(getUpload());
byte[] buffer = new byte[1024];
int len = 0;
while ((len = fis.read(buffer)) > 0) {
fos.write(buffer, 0, len);
}
fos.close();
fis.close();
return SUCCESS;
}
private String filterType(String[] types) {
String fileType = this.getUploadContentType();
for (String type : types) {
if (type.equals(fileType)) {
return null;
}
}
return INPUT;
}
private static String getExtention(String fileName) {
int pos = fileName.lastIndexOf(".");
return fileName.substring(pos);
}
}
------------------------------------- index.jsp --------------------------------------------------------
<%@page language="java" pageEncoding="UTF-8"%>
<%@taglib prefix="s" uri="/struts-tags"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
</head>
<body>
${requestScope.typeError}
<form action="upload.action" method="post" enctype="multipart/form-data">
<input type="file" name="upload" />
<br>
<input value="upload" type="submit" />
</form>
</body>
</html>
------------------------------------- success.jsp --------------------------------------------------------
<%@ page language="java" pageEncoding="UTF-8"%>
<%@taglib prefix="s" uri="/struts-tags"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
</head>
<body>
上传成功!
<br>
文件为:
<img src="<s:property value="'upload/' + uploadFileName"/>" />
<br>
</body>
</html>
------------------------------------- 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>
<!-- 设置struts2 上传文件时 保存的临时目录 -->
<constant name="struts.multipart.saveDir" value="C:\temp"></constant>
<!-- 配置上传是文件的最大限制为200M -->
<constant name="struts.multipart.maxSize" value="20971520" />
<constant name="struts.custom.i18n.resources" value="globalMessages" />
<constant name="struts.i18n.encoding" value="UTF-8" />
<package name="tntmanage" extends="struts-default" namespace="/">
<action name="upload" class="com.bse.action.UploadAction">
<param name="allowTypes">
image/pjpeg,image/bmp,image/jpg,image/png,image/x-png,image/gif,image/jpeg
</param>
<param name="savePath">/upload</param>
<result>/success.jsp</result>
<result name="input">/index.jsp</result>
</action>
</package>
</struts>
-------------------------------------- web.xml -----------------------------------------------------------
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
<display-name></display-name>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<!-- Struts2核心控制器 -->
<!-- <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>/*</url-pattern>
</filter-mapping> -->
<filter>
<filter-name>struts2</filter-name>
<filter-class>
org.apache.struts2.dispatcher.FilterDispatcher
</filter-class>
</filter>
<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<filter>
<filter-name>struts-cleanup</filter-name>
<filter-class>
org.apache.struts2.dispatcher.ActionContextCleanUp
</filter-class>
</filter>
<filter-mapping>
<filter-name>struts-cleanup</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>