Struts 2 简明教程
Struts 2 - File Uploads
Struts 2 框架提供内置的支持来使用“HTML 中基于表单的文件上传”处理文件上传。当上传一个文件时,它通常会存储在一个临时目录中,并应该由你的 Action 类处理或移动到一个永久目录中以确保数据不会丢失。
The Struts 2 framework provides built-in support for processing file upload using "Form-based File Upload in HTML". When a file is uploaded, it will typically be stored in a temporary directory and they should be processed or moved by your Action class to a permanent directory to ensure the data is not lost.
Note - 服务器可能会实施禁止写入临时目录和你 Web 应用程序所属目录之外的目录的安全策略。
Note − Servers may have a security policy in place that prohibits you from writing to directories other than the temporary directory and the directories that belong to your web application.
Struts 中的文件上传可以通过一个称为 FileUpload 的预定义拦截器来实现,可以通过类 org.apache.struts2.interceptor.FileUploadInterceptor 获得,并作为 defaultStack 的一部分包括其中。仍然可以在你自己的 struts.xml 中使用它来设置各种参数,如下所示。
File uploading in Struts is possible through a pre-defined interceptor called FileUpload interceptor which is available through the org.apache.struts2.interceptor.FileUploadInterceptor class and included as part of the*defaultStack*. Still you can use that in your struts.xml to set various paramters as we will see below.
Create View Files
让我们从创建我们的视图开始,该视图需要浏览和上传一个选定的文件。所以让我们创建一个 index.jsp ,带一个允许用户上传文件的简单 HTML 上传表单 −
Let us start with creating our view which will be required to browse and upload a selected file. So let us create an index.jsp with plain HTML upload form that allows the user to upload a file −
<%@ 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 。应该设置它以使文件上传拦截器成功处理文件上传。另一值得注意的是表单的 action 方法 upload 和文件上传字段的名称 - myFile 。我们需要这些信息来创建 action 方法和 struts 配置。
There is couple of points worth noting in the above example. First, the form’s enctype is set to multipart/form-data. This should be set so that file uploads are handled successfully by the file upload interceptor. The next point noting is the form’s action method upload and the name of the file upload field - which is myFile. We need this information to create the action method and the struts configuration.
接下来,让我们创建一个 success.jsp 以显示在文件上传成功后我们的结果。
Next, let us create a simple jsp file success.jsp to display the outcome of our file upload in case it becomes success.
<%@ 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 的结果文件,如果在上传文件时有一些错误 −
Following will be the result file error.jsp in case there is some error in uploading the file −
<%@ 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>
Create Action Class
接下来,让我们创建称为 uploadFile.java 的 Java 类,它将负责上传文件并将该文件存储在一个安全的位置中 −
Next, let us create a Java class called uploadFile.java which will take care of uploading file and storing that file at a secure location −
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 拦截器为我们完成了所有繁重的任务。
The uploadFile.java is a very simple class. The important thing to note is that the FileUpload interceptor along with the Parameters Interceptor does all the heavy lifting for us.
FileUpload 拦截器默认情况下为你提供三个参数。它们按照以下模式命名 −
The FileUpload interceptor makes three parameters available for you by default. They are named in the following pattern −
-
*[your file name parameter] * − This is the actual file that the user has uploaded. In this example it will be "myFile"
-
[your file name parameter]ContentType − This is the content type of the file that was uploaded. In this example it will be "myFileContentType"
-
[your file name parameter]FileName − This is the name of the file that was uploaded. In this example it will be "myFileFileName"
这三个参数可供我们使用,这要归功于 Struts 拦截器。我们必须做的就是用正确的名称在我们的 Action 类中创建三个参数,这些变量将自动为我们自动连接。因此,在上面的示例中,我们有三个参数,一个行动方法,如果一切都好,它会返回“成功”,否则它将返回“错误”。
The three parameters are available for us, thanks to the Struts Interceptors. All we have to do is to create three parameters with the correct names in our Action class and automatically these variables are auto wired for us. So, in the above example, we have three parameters and an action method that simply returns "success" if everything goes fine otherwise it returns "error".
Configuration Files
以下是控制文件上传过程的 Struts2 配置属性:
Following are the Struts2 configuration properties that control file uploading process −
Sr.No |
Properties & Description |
1 |
struts.multipart.maxSize The maximum size (in bytes) of a file to be accepted as a file upload. Default is 250M. |
2 |
struts.multipart.parser The library used to upload the multipart form. By default is jakarta |
3 |
struts.multipart.saveDir The location to store the temporary file. By default is javax.servlet.context.tempdir. |
为了更改这些设置中的任何一个,您可以在应用程序的 struts.xml 文件中使用 constant 标记,如我所做的那样,将上传的文件的最大大小更改为。
In order to change any of these settings, you can use constant tag in your applications struts.xml file, as I did to change the maximum size of a file to be uploaded.
让我们将我们的 struts.xml 设置为以下内容:
Let us have our struts.xml as follows −
<?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 。
Since, FileUpload interceptor is a part of the default Stack of interceptors, we do not need to configure it explicity. But, you can add <interceptor-ref> tag inside <action>. The fileUpload interceptor takes two parameters (a) maximumSize and (b) allowedTypes.
maximumSize 参数设置允许的最大文件大小(默认大小约为 2MB)。allowedTypes 参数是以逗号分隔的已接受内容(MIME)类型的列表,如下所示:
The maximumSize parameter sets the maximum file size allowed (the default is approximately 2MB). The allowedTypes parameter is a comma-separated list of accepted content (MIME) types as shown below −
<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 文件的内容:
Following is the content of web.xml file −
<?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>
现在右键单击项目名称,然后单击 Export > WAR File 以下创建 War 文件。然后将此 WAR 部署在 Tomcat 的 webapps 目录中。最后,启动 Tomcat 服务器并尝试访问 URL http://localhost:8080/HelloWorldStruts2/upload.jsp 。这将生成以下屏幕:
Now Right click on the project name and click Export > WAR File to create a War file. Then deploy this WAR in the Tomcat’s webapps directory. Finally, start Tomcat server and try to access URL http://localhost:8080/HelloWorldStruts2/upload.jsp. This will produce the following screen −
现在使用“浏览”按钮选择文件“Contacts.txt”,然后单击上传按钮,该按钮将在您的服务上上传文件,您应该会看到下一页。您可以检查上传的文件是否已保存在 C:\apache-tomcat-6.0.33\work 中。
Now select a file "Contacts.txt" using Browse button and click upload button which will upload the file on your serve and you should see the next page. You can check the uploaded file should be saved in C:\apache-tomcat-6.0.33\work.
请注意,FileUpload 拦截器会自动删除上传的文件,因此您必须在文件被删除之前以编程方式将上传的文件保存在某个位置。
Note that the FileUpload Interceptor deletes the uploaded file automatically so you would have to save uploaded file programmatically at some location before it gets deleted.
Error Messages
fileUplaod 拦截器使用几个默认的错误消息键:
The fileUplaod interceptor uses several default error message keys −
Sr.No |
Error Message Key & Description |
1 |
struts.messages.error.uploading A general error that occurs when the file could not be uploaded. |
2 |
struts.messages.error.file.too.large Occurs when the uploaded file is too large as specified by maximumSize. |
3 |
struts.messages.error.content.type.not.allowed Occurs when the uploaded file does not match the expected content types specified. |
您可以在 WebContent/WEB-INF/classes/messages.properties 资源文件中覆盖这些消息的文本。
You can override the text of these messages in WebContent/WEB-INF/classes/messages.properties resource files.