創(chuàng)建視圖時(shí)需要瀏覽和上傳選定的文件。因此,讓我們先使用HTML上傳表單,創(chuàng)建一個(gè)允許用戶上傳文件的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)值得注意。首先,表單的enctype設(shè)置為multipart/form-data,要使得文件上傳攔截器成功處理文件上傳,這個(gè)就必須設(shè)置。然后要注意的是表單的action方法上傳和文件上傳字段的名稱(即myFile)。我們需要這些信息來創(chuàng)建action方法和struts配置。
<%@ 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,一旦上傳文件出錯(cuò)時(shí)會(huì)使用:
<%@ 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)建一個(gè)名為uploadFile.java的Java類,它將負(fù)責(zé)上傳文件并將文件存儲(chǔ)在安全的位置:
package cn.w3cschool.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是一個(gè)非常簡(jiǎn)單的類。要注意的重點(diǎn)是,F(xiàn)ileUpload攔截器和Parameters攔截器為我們承擔(dān)了所有的重工作量。默認(rèn)情況下,F(xiàn)ileUpload攔截器為你提供三個(gè)參數(shù),它們分別按以下方式命名:
[文件名參數(shù)] - 這是用戶已上傳的實(shí)際文件。在這個(gè)例子中它將是“myFile”
[文件名參數(shù)]ContentType - 這是上傳的文件的內(nèi)容類型。在這個(gè)例子中,它將是“myFileContentType”
[文件名參數(shù)]FileName - 這是上傳的文件的名稱。在這個(gè)例子中,它將是“myFileFileName”
得益于Struts攔截器這三個(gè)參數(shù)均可供我們使用。我們要做的是在Action類中創(chuàng)建三個(gè)帶有正確名稱的參數(shù),并使這些變量可以自動(dòng)連接。所以,在上面的例子中,我們有三個(gè)參數(shù)和一個(gè)action方法。如果一切正常,則返回“success”,否則返回“error”。
以下是控制文件上傳過程的Struts2 配置屬性:
序號(hào) | 屬性和說明 |
---|---|
1 | struts.multipart.maxSize 可接受的上傳文件的最大值(以字節(jié)為單位),默認(rèn)值為250M。 |
2 | struts.multipart.parser 用于上傳多部分表單的庫,默認(rèn)為jakarta。 |
3 | struts.multipart.saveDir 存儲(chǔ)臨時(shí)文件的位置,默認(rèn)是javax.servlet.context.tempdir。 |
你可以在應(yīng)用程序的struts.xml文件中使用constant標(biāo)簽更改任意一個(gè)這些設(shè)置,我們可以看以下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="cn.w3cschool.struts2.uploadFile"> <result name="success">/success.jsp</result> <result name="error">/error.jsp</result> </action> </package> </struts>
因?yàn)?strong>FileUpload攔截器是defaultStack攔截器的一部分,我們不需要準(zhǔn)確的配置它,但你可以在<action>中添加<interceptor-ref>標(biāo)簽。fileUpload攔截器有兩個(gè)參數(shù):maximumSize和allowedTypes。 maximumSize參數(shù)是設(shè)置所允許的文件大小的最大值(默認(rèn)約為2MB)。allowedTypes參數(shù)是所允許的內(nèi)容(MIME)類型的用逗號(hào)分隔的列表,如下所示:
<action name="upload" class="cn.w3cschool.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)在右鍵單擊項(xiàng)目名稱,然后單擊“Export”>“WAR File”創(chuàng)建WAR文件。然后在Tomcat的webapps目錄中部署WAR文件。最后,啟動(dòng)Tomcat服務(wù)器并嘗試訪問URL http://localhost:8080/HelloWorldStruts2/upload.jsp,將顯示如下界面:
現(xiàn)在使用瀏覽按鈕選擇一個(gè)文件“Contacts.txt”,然后點(diǎn)擊上傳按鈕,上傳文件到服務(wù)器,你將看到如下頁面。你上傳的文件應(yīng)該保存在C:\apache-tomcat-6.0.33\work下。
注意:FileUpload攔截器會(huì)自動(dòng)刪除上傳的文件,因此你必須在上傳的文件被刪除之前將其以編程方式保存在某個(gè)位置。
fileUplaod攔截器使用幾個(gè)默認(rèn)的錯(cuò)誤信息key:
序號(hào) | 錯(cuò)誤信息key和說明 |
---|---|
1 | struts.messages.error.uploading 無法上傳文件時(shí)發(fā)生的常規(guī)錯(cuò)誤。 |
2 | struts.messages.error.file.too.large 當(dāng)上傳的文件過大(由maximumSize指定)時(shí)發(fā)生。 |
3 | struts.messages.error.content.type.not.allowed 當(dāng)上傳的文件與指定的預(yù)期內(nèi)容類型不匹配時(shí)發(fā)生。 |
你可以在WebContent/WEB-INF/classes/messages.properties資源文件中覆蓋這些消息文本。
更多建議: