简介:
使用 struts2 和 spring 实现的一个简单的图片上传。
依赖:
Spring IoC相关jar包:
IoC:
commons-logging.jar
spring-beans-*.RELEASE.jar
spring-context-*.RELEASE.jar
spring-core-*.RELEASE.jar
spring-expression-*.RELEASE.jar
struts2需要jar包:
commons-fileupload-1.3.1.jar
commons-io-2.2.jar
commons-lang3-3.2.jar
freemarker-2.3.19.jar
javassist-3.11.0.GA.jar
log4j-1.2.17.jar
ognl-3.0.6.jar
struts2-core-2.3.20.jar
xwork-core-2.3.20.jar
web.xml配置:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" version="3.0">
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</context-param>
<display-name>Strtus2FileUpLoad</display-name>
<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>
</web-app>
applicationContext.xml配置:
<!-- 扫描Srping组件 -->
<context:component-scan base-package="action"></context:component-scan>
<context:component-scan base-package="impl"></context:component-scan>
<context:component-scan base-package="service"></context:component-scan>
<!-- 载入上传类型设置 -->
<util:properties id="uploadType" location="classpath:upload.properties"></util:properties>
struts.xml配置:
<struts>
<package name="fileUpLoad" namespace="/file" extends="struts-default">
<!-- 使用spring注入Action -->
<action name="upload" class="uploadAction">
<result name="success">/success.jsp</result>
<result name="error">/error.jsp</result>
</action>
</package>
</struts>
配置文件properties:
struts.properties配置:
#struts setting file
#Priority is higher than the XML configuration file
#set max size 2M
struts.multipart.maxSize=2097152
#set temp save dir
struts.multipart.saveDir=uptemp
#set encoding
struts.i18n.encoding=UTF-8
#set load multiple custom properties split for ,
struts.custom.properties=,
upload.properties配置:
设置允许上传的文件类型
#set upload type split by ','
upload.type.image=jpeg,png,gif
DAO层代码:
@Repository("uploadImpl")
public class FileUpLoadDAOImpl implements FileUpLoadDAO {
/**
* 复制struts上传的临时文件到指定目录
* @param src 上传的文件
* @param dest 指定目录
* @return
*/
public void copy(File src, File dest) throws Exception {
BufferedInputStream bis = new BufferedInputStream(new FileInputStream(src));
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(dest));
byte [] buf = new byte [1024];
@SuppressWarnings("unused")
int len = -1;
while((len = bis.read(buf)) != -1) {
bos.write(buf);
}
bis.close();
bos.close();
}
/**
* 保存文件路径
* @param path
*/
public void savePath(String path) throws Exception {
//保存文件路径到数据库
}
}
Service层代码
@Service("uploadService")
public class FileUpLoadService {
@Resource(name="uploadImpl")
private FileUpLoadDAO fileUpLoad;
/**
* 上传图片
* @param src
* @param dest
* @return
*/
public boolean upload(File src, File dest){
try {
fileUpLoad.copy(src, dest);
} catch (Exception e) {
e.printStackTrace();
return false;
}
return true;
}
/**
* 保存图片路径
* @param path
* @return
*/
public boolean savePath(String path) {
//保存成功返回true,失败返回false
try {
fileUpLoad.savePath(path);
} catch (Exception e) {
e.printStackTrace();
return false;
}
return true;
}
}
action代码:
/**
* 用于执行文件上传的Action
* @author haifeng
*
*/
@Component("uploadAction")
public class FileUpLoadAction {
private File file; //拦截器传入的临时文件,变量命名方式[和文件上传空间的name一致]
private String fileFileName;//拦截器注入的原始文件名,变量命名方式[*FileName]
private String fileContentType; // 上传文件类型,变量命名方式[*ContentType],用于限制文件类型
@Resource(name="uploadService")
private FileUpLoadService upLoadService;
@Resource(name="uploadType")
private Properties properties;
/**
* 执行文件上传
* @return
* @throws Exception
*/
public String execute() throws Exception {
//获取配置文件中设置的文件类型,用,分割
String prop = properties.getProperty("upload.type.image");
String [] types = prop.split(",");
if(types.length>0 && types!=null)
for(String t : types) {
//判断是否有符合要求的文件类型
//由于图片的分类都是以image/开头,为避免不必要的重复书写,直接在程序里进行拼接,以简化配置文件
//忽略大小写
if(("image/"+t).equalsIgnoreCase(fileContentType)) {
//执行上传逻辑
//截取文件后缀
String suffix = fileFileName.substring(fileFileName.lastIndexOf("."));
//根据当前系统时间毫秒值生成新的文件名
String newName = Calendar.getInstance().getTimeInMillis() + suffix;
//根据项目部署路径计算文件上传的完整路径
String path = ServletActionContext.getServletContext().getRealPath("/upload/"+newName);
//将临时文件复制到上传路径下
boolean flag = upLoadService.upload(file, new File(path));
if(!flag){
return "error";
}
//保存路径到数据库
flag = upLoadService.savePath(path);
if(!flag) {
return "error";
}
}
}
return "error";
}
public File getFile() {
return file;
}
public void setFile(File file) {
this.file = file;
}
public String getFileFileName() {
return fileFileName;
}
public void setFileFileName(String fileFileName) {
this.fileFileName = fileFileName;
}
public String getFileContentType() {
return fileContentType;
}
public void setFileContentType(String fileContentType) {
this.fileContentType = fileContentType;
}
}
upload.jsp
<form action="file/upload.action" enctype="multipart/form-data" method="POST">
<input type="file" name="file">
<input type="submit" value="上传">
</form>