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>
接下来让我们创建一个java类称为 uploadfile.java 这会处理上传文件,该文件存储在一个安全的位置:
package com.h3.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.h3.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.h3.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。这会给出以下画面:
现在选择一个文件的“contacts.txt”使用“浏览”按钮,然后点击上传按钮,将文件上传,应该看到页面。可以检查上传的文件保存在 c:apache-tomcat-6.0.33work.
请注意,使用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.