当前位置: 首页 > 教程 > Struts2 >

Struts2 文件上传

精华
小牛编辑
166浏览
2023-03-14

Struts 2框架提供了内置支持处理文件上传使用基于HTML表单的文件上传。上传一个文件时,它通常会被存储在一个临时目录中,他们应该由Action类进行处理或移动到一个永久的目录,以确保数据不丢失。

请注意,服务器有一个安全策略可能会禁止写到目录以外的临时目录和属于web应用的目录。

在Struts中的文件上传是通过预先定义的拦截文件上传拦截器这是可通过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。这应该是设置为使得处理文件上传文件上传。下一个点值得注意的是表单的 action方法上传和文件上传字段的名称 - myFile。我们需要这些信息创建操作方法和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>

创建action类:

接下来让我们创建一个Java类称为 uploadFile.java 这会处理上传文件,该文件存储在一个安全的位置:

package com.yiibai.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拦截器随着参数Intercetpor 确实为我们解决所有繁重工作。文件上传拦截器,使三个参数,默认情况下提供。它们被命名为以下模式:

  • [your file name parameter] - 这是实际的文件的上载。在这个例子中是 "myFile"

  • [your file name parameter]ContentType - 这是被上传的文件,该文件的内容类型。在这个例子中是 "myFileContentType"

  • [your file name parameter]FileName - 这是被上传的文件的名称。在这个例子中是 "myFileFileName"

这三个参数是为我们提供的,这要归功于Struts的拦截器。所有我们需要做的是在我们的Action类,这些变量是自动连线我们以正确的名称创建三个参数。所以,在上面的例子中,我们有三个参数的操作方法简单地返回“success”,如果一切顺利,否则返回“error”。

配置文件:

以下是Struts2的配置属性可以控制文件上传过程:

SN 属性& 描述
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文件,像我一样改变要上传的文件的最大大小。让我们有我们的在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.yiibai.struts2.uploadFile">
       <result name="success">/success.jsp</result>
       <result name="error">/error.jsp</result>
   </action>
   </package>
</struts>

由于FileUpload拦截器是拦截器defaultStack的一部分,我们并不需要明确地配置。但可以添加<interceptor-ref>标签到<action>里面。文件上传拦截器需要两个参数:(a)maximumSize及(b)allowedTypes。maximumSize参数设置允许的最大文件大小(默认为约2MB)。allowedTypes参数接受的内容是一个逗号分隔的列表(MIME)类型,如下所示:

   <action name="upload" class="com.yiibai.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>

现在右键点击项目名称,并单击 Export > WAR File 创建一个WAR文件。然后部署此WAR在Tomcat 的webapps目录下。最后,启动Tomcat服务器和尝试访问URL http://localhost:8080/HelloWorldStruts2/upload.jsp。这会给出以下画面:

File Upload

现在选择一个文件的“Contacts.txt”使用“浏览”按钮,然后点击上传按钮,将文件上传,应该看到页面。可以检查上传的文件保存在 C:apache-tomcat-6.0.33work.

File Upload Result

请注意,使用FileUpload拦截删除上传的文件自动所以需要编程在一些位置上保存上传的文件被删除之前。

错误消息:

fileUplaod拦截器使用几个默认的错误消息键:

SN 错误消息键 & 描述
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.

You can override the text of these messages in WebContent/WEB-INF/classes/messages.propertiesresource files.