更新時間:2021-11-12 08:55:33 來源:動力節點 瀏覽1234次
Struts2 框架為使用“HTML 格式的基于表單的文件上傳”處理文件上傳提供了內置支持。當一個文件被上傳時,它通常會被存儲在一個臨時目錄中,它們應該被你的 Action 類處理或移動到一個永久目錄中,以確保數據不會丟失。
注意- 服務器可能有一個安全策略,禁止您寫入臨時目錄和屬于您的 Web 應用程序的目錄以外的目錄。
Struts 中的文件上傳可以通過名為FileUpload攔截器的預定義攔截器實現,該攔截器可通過 org.apache.struts2.interceptor.FileUploadInterceptor 類獲得,并作為defaultStack 的一部分包含在內。您仍然可以在 struts.xml 中使用它來設置各種參數,我們將在下面看到。
讓我們從創建瀏覽和上傳選定文件所需的視圖開始。因此,讓我們創建一個帶有純 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>
在上面的例子中有幾點值得注意。首先,表單的 enctype 設置為multipart/form-data。應設置此項,以便文件上傳攔截器成功處理文件上傳。下一點要注意的是表單的操作方法upload和文件上傳字段的名稱 - 這是myFile。我們需要這些信息來創建 action 方法和 struts 配置。
接下來,讓我們創建一個簡單的 jsp 文件success.jsp來顯示我們文件上傳的結果,以防它成功。
<%@ 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>
以下將是結果文件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>
接下來,讓我們創建一個名為uploadFile.java的 Java 類,它將負責上傳文件并將該文件存儲在一個安全的位置
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是一個非常簡單的類。需要注意的重要一點是 FileUpload 攔截器和 Parameters Interceptor 一起為我們完成了所有繁重的工作。
FileUpload 攔截器默認為您提供三個參數。它們以以下模式命名 -
[您的文件名參數] - 這是用戶上傳的實際文件。在這個例子中,它將是“myFile”
[您的文件名參數]ContentType - 這是上傳文件的內容類型。在這個例子中,它將是“myFileContentType”
[您的文件名參數]FileName - 這是上傳的文件的名稱。在這個例子中,它將是“myFileFileName”
由于 Struts 攔截器,我們可以使用這三個參數。我們所要做的就是在我們的 Action 類中創建三個具有正確名稱的參數,這些變量會自動為我們自動連接。所以,在上面的例子中,我們有三個參數和一個 action 方法,如果一切正常,它只會返回“success”,否則返回“error”。
以下是控制文件上傳過程的 Struts2 配置屬性
序號 |
屬性和描述 |
---|---|
1 |
struts.multipart.maxSize 要作為文件上傳接受的文件的最大大小(以字節為單位)。默認為 250M。 |
2 |
struts.multipart.parser 用于上傳多部分表單的庫。默認是jakarta |
3 |
struts.multipart.saveDir 存儲臨時文件的位置。默認情況下是 javax.servlet.context.tempdir。 |
為了更改這些設置中的任何一個,您可以在應用程序 struts.xml 文件中使用常量標記,就像我更改要上傳的文件的最大大小一樣。
讓我們的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>
由于FileUpload攔截器是默認攔截器堆棧的一部分,我們不需要明確配置它。但是,您可以在<action>中添加<interceptor-ref>標簽。fileUpload 攔截器采用兩個參數 (a) maximumSize和(b) allowedTypes。
maximumSize 參數設置允許的最大文件大小(默認值約為 2MB)。allowedTypes 參數是一個逗號分隔的接受內容 (MIME) 類型列表,如下所示
<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文件的內容
<?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>
現在右鍵單擊項目名稱并單擊“導出”>“WAR 文件”以創建一個 War 文件。然后將此 WAR 部署到 Tomcat 的 webapps 目錄中。最后,啟動Tomcat服務器并嘗試訪問URLhttp://localhost:8080/HelloWorldStruts2/upload.jsp。這將產生以下屏幕
現在使用瀏覽按鈕選擇一個文件“Contacts.txt”,然后單擊上傳按鈕,將文件上傳到您的服務器,您應該會看到下一頁。您可以檢查上傳的文件應該保存在 C:\apache-tomcat-6.0.33\work 中。
請注意,FileUpload Interceptor 會自動刪除上傳的文件,因此您必須在刪除之前以編程方式將上傳的文件保存在某個位置。
fileUplaod 攔截器使用幾個默認的錯誤消息鍵
序號 |
錯誤信息鍵和描述 |
---|---|
1 |
struts.messages.error.uploading 無法上傳文件時發生的一般錯誤。 |
2 |
struts.messages.error.file.too.large 當上傳的文件過大(由maximumSize 指定)時發生。 |
3 |
struts.messages.error.content.type.not.allowed 當上傳的文件與指定的預期內容類型不匹配時發生。 |
可以在WebContent/WEB-INF/classes/messages.properties資源文件中覆蓋這些消息的文本。
以上就是關于“Struts2上傳文件詳解”的介紹,如果大家想了解更多相關知識,不妨來關注一下動力節點的Struts2視頻教程,里面的內容豐富,通俗易懂,適合小白學習,希望對大家能夠有所幫助。
0基礎 0學費 15天面授
有基礎 直達就業
業余時間 高薪轉行
工作1~3年,加薪神器
工作3~5年,晉升架構
提交申請后,顧問老師會電話與您溝通安排學習