温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

Struts2上传文件的方法是什么

发布时间:2022-09-29 11:45:03 来源:亿速云 阅读:83 作者:iii 栏目:开发技术

这篇文章主要介绍“Struts2上传文件的方法是什么”的相关知识,小编通过实际案例向大家展示操作过程,操作方法简单快捷,实用性强,希望这篇“Struts2上传文件的方法是什么”文章能帮助大家解决问题。

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。这将产生以下屏幕

Struts2上传文件的方法是什么

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

Struts2上传文件的方法是什么

请注意,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上传文件的方法是什么”的内容就介绍到这里了,感谢大家的阅读。如果想了解更多行业相关的知识,可以关注亿速云行业资讯频道,小编每天都会为大家更新不同的知识点。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI