簡介:
使用 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>