Struts 2 框架為處理文件上傳提供了內(nèi)置支持,它使用“在 HTML 中基于表單的文件上傳”。當(dāng)上傳一個文件時,它通常會被存儲在一個臨時目錄中,而且它們應(yīng)該由 Action 類進(jìn)行處理或移動到一個永久的目錄,用來確保數(shù)據(jù)不丟失。
注意服務(wù)器在恰當(dāng)?shù)奈恢每赡苡幸粋€安全策略,它會禁止你寫到除了臨時目錄以外的目錄,而且這個目錄屬于你的web應(yīng)用應(yīng)用程序。
通過預(yù)定義的名為文件上傳的攔截器,Struts 的文件上傳是可能的,這個攔截器在 org.apache.struts2.interceptor.FileUploadInterceptor 類是可用的,而且是 defaultStack 的一部分。你仍然可以使用在 struts.xml 中設(shè)置各種參數(shù),我們將在下面看到。
讓我們開始創(chuàng)建需要瀏覽和上傳選定的文件的視圖。因此,讓我們創(chuàng)建一個帶有簡單的 HTML 上傳表單的 index.jsp,它允許用戶上傳文件:
<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%> <%@ taglib prefix="s" uri="/struts-tags"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <title>File Upload</title> </head> <body> <form action="upload" method="post" enctype="multipart/form-data"> <label for="myFile">Upload your file</label> <input type="file" name="myFile" /> <input type="submit" value="Upload"/> </form> </body> </html>
在上面的例子中有幾點(diǎn)值得注意。首先,表單的編碼類型設(shè)置為 multipart/form-data。為了使用文件上傳攔截器來成功地處理文件上傳,它應(yīng)該被設(shè)置。下一個注意點(diǎn)是表單的動作方法 upload 和文件上傳字段的名稱是 myFile。我們需要這些信息來創(chuàng)建動作方法和 struts 配置。
接下來讓我們創(chuàng)建一個簡單的 jsp 文件 success.jsp 來顯示我們的文件上傳的結(jié)果,假使它成功地執(zhí)行。
<%@ page contentType="text/html; charset=UTF-8" %> <%@ taglib prefix="s" uri="/struts-tags" %> <html> <head> <title>File Upload Success</title> </head> <body> You have successfully uploaded <s:property value="myFileFileName"/> </body> </html>
下面是結(jié)果文件 error.jsp,假使在上傳文件過程中有一些錯誤:
<%@ page contentType="text/html; charset=UTF-8" %> <%@ taglib prefix="s" uri="/struts-tags" %> <html> <head> <title>File Upload Error</title> </head> <body> There has been an error in uploading the file. </body> </html>
接下來讓我們創(chuàng)建一個稱為 uploadFile.java 的 Java 類,它負(fù)責(zé)上傳文件,并且把這個文件存儲在一個安全的位置:
package com.tutorialspoint.struts2;
import java.io.File;
import org.apache.commons.io.FileUtils;
import java.io.IOException;
import com.opensymphony.xwork2.ActionSupport;
public class uploadFile extends ActionSupport{
private File myFile;
private String myFileContentType;
private String myFileFileName;
private String destPath;
public String execute()
{
/* Copy file to a safe location */
destPath = "C:/apache-tomcat-6.0.33/work/";
try{
System.out.println("Src File name: " + myFile);
System.out.println("Dst File name: " + myFileFileName);
File destFile = new File(destPath, myFileFileName);
FileUtils.copyFile(myFile, destFile);
}catch(IOException e){
e.printStackTrace();
return ERROR;
}
return SUCCESS;
}
public File getMyFile() {
return myFile;
}
public void setMyFile(File myFile) {
this.myFile = myFile;
}
public String getMyFileContentType() {
return myFileContentType;
}
public void setMyFileContentType(String myFileContentType) {
this.myFileContentType = myFileContentType;
}
public String getMyFileFileName() {
return myFileFileName;
}
public void setMyFileFileName(String myFileFileName) {
this.myFileFileName = myFileFileName;
}
}
uploadFile.java 是一個非常簡單的類。值得注意的一件重要的事情是文件上傳攔截器和參數(shù)攔截器為我們處理所有繁重的工作。文件上傳攔截器在默認(rèn)情況下有三個可用的參數(shù)。它們被命名為下列模式:
[your file name parameter] –這是實(shí)際的用戶已經(jīng)上傳的文件。在這個例子中它是 “myFile”。
[your file name parameter]ContentType - 這是被上傳的文件的內(nèi)容類型。在這個例子中它是 “myFileContentType”。
對我們來說,這三個參數(shù)是可用的,這要?dú)w功于 Struts 的攔截器。我們要做的是在我們的動作類中用正確的名稱創(chuàng)建三個參數(shù),而且這些變量是為我們自動連線的。所以,在上面的例子中,我們有三個參數(shù)和一個動作方法,如果一切正常,則簡單地返回 “success”,否則返回 “error”。
下面是可以控制文件上傳過程的 Struts2 的配置屬性:
序號 | 屬性 & 描述 |
---|---|
1 |
struts.multipart.maxSize
當(dāng)一個文件上傳時,可以接受的最大的文件大小(以字節(jié)為單位)。默認(rèn)設(shè)置是 250 M。 |
2 |
struts.multipart.parser
用于上傳多個表單的庫。默認(rèn)情況下是 jakarta。 |
3 |
struts.multipart.saveDir
存儲臨時文件的位置。默認(rèn)情況下是 javax.servlet.context.tempdir。 |
為了改變這些設(shè)置,你可以使用在你的應(yīng)用程序 struts.xml 文件中 constant 標(biāo)簽,就像我改變上傳文件的最大大小的操作。讓我們有如下所示的 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>
<constant name="struts.devMode" value="true" />
<constant name="struts.multipart.maxSize" value="1000000" />
<package name="helloworld" extends="struts-default">
<action name="upload" class="com.tutorialspoint.struts2.uploadFile">
<result name="success">/success.jsp</result>
<result name="error">/error.jsp</result>
</action>
</package>
</struts>
由于攔截器是攔截器 defaultStack 的一部分,我們并不需要明確地配置它。但是你可以在
<action name="upload" class="com.tutorialspoint.struts2.uploadFile">
<interceptor-ref name="basicStack">
<interceptor-ref name="fileUpload">
<param name="allowedTypes">image/jpeg,image/gif</param>
</interceptor-ref>
<result name="success">/success.jsp</result>
<result name="error">/error.jsp</result>
</action>
下面是 web.xml 文件的內(nèi)容:
<?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"
xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
id="WebApp_ID" version="3.0">
<display-name>Struts 2</display-name>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<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>
</web-app>
現(xiàn)在,在項目名稱上點(diǎn)擊右鍵,并且單擊 Export > WAR File 來創(chuàng)建一個 War 文件。然后在 Tomcat 的 webapps 目錄下部署這個 WAR。最后,啟動 Tomcat 服務(wù)器和嘗試訪問 URL http://localhost:8080/HelloWorldStruts2/upload.jsp
. 將會給出下面的畫面:
http://wiki.jikexueyuan.com/project/struts-2/images/helloworldstruts7.jpg" alt="" />
現(xiàn)在使用瀏覽按鈕選擇一個文件 “Contacts.txt”,而且單擊上傳按鈕,它將在你的服務(wù)器上上傳文件,然后你應(yīng)該看到頁面。你可以查看保存在 C:\apache-tomcat-6.0.33\work 中上傳的文件。
http://wiki.jikexueyuan.com/project/struts-2/images/helloworldstruts8.jpg" alt="" />
注意文件上傳攔截器自動刪除上傳的文件,所以你需要通過編程在某個位置上保存上傳的文件,在它被刪除之前。
文件上傳攔截器使用幾個默認(rèn)的錯誤消息鍵:
序號 | 錯誤消息鍵 & 描述 |
---|---|
1 |
struts.messages.error.uploading
一個發(fā)生在文件無法上傳時的通常的錯誤。 |
2 |
struts.messages.error.file.too.large
發(fā)生在上傳文件比指定的 maximumSize 大時。 |
3 |
struts.messages.error.content.type.not.allowed
發(fā)生在上傳文件不匹配指定的預(yù)期內(nèi)容類型。 |
你可以重寫在 WebContent/WEB-INF/classes/messages.properties 源文件中消息的內(nèi)容。