It is easy to upload and download files by using Commons FileUpload components in Struts2, Commons fileupload by saving HTTP data to a temporary folder. Struts then uses the FileUpload interceptor to bind the file to an instance of the action, so that we can manipulate the browser upload file as a local file. However, most of these examples need to be configured in the Struts.xml, more cumbersome, but the STRUTS2 provides a Struts2-convention-plugin plug-in, you can use annotations in the program to configure the action to make it more flexible.
The following is an introduction to using annotations to implement file uploads:
1. Add a dependent Jar pack
2. Configure Struts.xml files, where the struts file basically does not need to configure, such as:
<?xml version= "1.0" encoding= "UTF-8"?> <!
DOCTYPE struts public
"-//apache Software foundation//dtd struts Configuration 2.3//en"
"http:// Struts.apache.org/dtds/struts-2.3.dtd ">
<struts>
<constant name=" Struts.enable.DynamicMethodInvocation "value=" true "/> <constant name=" Struts.devmode "value=
" true "/>
<constant name= "struts.convention.package.locators" value= "action"/>
<!--Specify the maximum number of bytes allowed to upload. The default value is 2097152 (2M), using the struts constant to enlarge the default upload file size-->
<constant name= "struts.multipart.maxSize" value= "104857600" ></constant>
</struts>
3. Write the file upload Action:FileUploadAction.java
Package com.figo.action;
Import Java.io.BufferedInputStream;
Import Java.io.BufferedOutputStream;
Import Java.io.File;
Import Java.io.FileInputStream;
Import Java.io.FileOutputStream;
Import Java.io.InputStream;
Import Java.io.OutputStream;
Import Org.apache.struts2.ServletActionContext;
Import org.apache.struts2.convention.annotation.Action;
Import Org.apache.struts2.convention.annotation.InterceptorRef;
Import Org.apache.struts2.convention.annotation.InterceptorRefs;
Import Org.apache.struts2.convention.annotation.Result;
Import Org.apache.struts2.convention.annotation.Results;
Import Com.opensymphony.xwork2.ActionSupport; @Action ("FileUpload") @InterceptorRefs (value = {@InterceptorRef ("Fileuploadstack")}) @Results ({@Result (name = Success ", location ="/result.jsp ")}) public class Fileuploadaction extends Actionsupport {private static final long s
Erialversionuid = 572146812454l;
private static final int buffer_size = 16 * 1024;
Encapsulates the properties of an uploaded file field private file upload; Encapsulation onAttributes of the file type private String contentType;
Encapsulates the attributes of an uploaded file name private String filename;
Private String Storagefilename;
Private String Storagepath; Since we are using <s:file name= "Upload" .../> The file itself'll be//obtained through Getter/setter
;file-tag-name> Public File Getupload () {return upload;
The public void Setupload (File upload) {this.upload = upload;
Public String GetFileName () {return fileName;
public void Setfilename (String fileName) {this.filename = filename; }//Since we are using <s:file name= "Upload" .../> the file name would be//obtained through getter/setter of &L
T;file-tag-name>filename public String Getuploadfilename () {return FileName;
public void Setuploadfilename (String fileName) {this.filename = filename;
Public String Getstoragefilename () {return storagefilename;
} public void Setstoragefilename (String storagefilename) {this.storagefilename = Storagefilename; }//SinCe we are using <s:file name= "Upload" .../> the content type would be//obtained through getter/setter of <file
-tag-name>contenttype public String Getuploadcontenttype () {return ContentType;
} public void Setuploadcontenttype (String contentType) {this.contenttype = ContentType;
Public String getContentType () {return contentType;
} public void setContentType (String contentType) {this.contenttype = ContentType;
public void copy (file src, file dst) {try {inputstream in = null;
OutputStream out = null;
try {in = new Bufferedinputstream (new FileInputStream (SRC), buffer_size);
out = new Bufferedoutputstream (new FileOutputStream (DST), buffer_size);
byte[] buffer = new Byte[buffer_size];
while (in.read (buffer) > 0) {out.write (buffer);
finally {if (null!= in) {in.close ();
} if (null!= out) {out.close ();
A catch (Exception e) {e.printstacktrace ()); } public static string Getextention (string fileName) {int pos = Filename.lastindexof (".");
Return filename.substring (POS); @Override public String Execute () throws Exception {//Storagefilename = new Date (). GetTime () + getextention (filen
AME);
Storagefilename = FileName;
SYSTEM.OUT.PRINTLN ("FileName:" + filename);
System.out.println ("ContentType:" + ContentType);
System.out.println ("File:" + upload);
File Storagefile = new file (Servletactioncontext.getservletcontext (). Getrealpath ("/upload") + "/" + storagefilename);
Copy (upload, storagefile);
return SUCCESS; }
}
The fileuploadaction role is to copy the uploaded files from the browser to the upload folder of the Web application.
4. Write the Document upload form page upload.jsp:
<%@ page language= "java" contenttype= "text/html; Charset=utf-8 "
pageencoding=" Utf-8 "%>
<%@ taglib prefix=" s "uri="/struts-tags "%>
<! DOCTYPE HTML PUBLIC "-//W3C//DTD XHTML 1.0 transitional//en" "Http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd ">
Set the form's submission to post, and then set Enctype to Multipart/form-data, <s:file/> flag binds the file upload control to the upload property of the action.
5. Results return page result.jsp:
<%@ page language= "java" contenttype= "Text/html;charset=utf-8"
pageencoding= "Utf-8"%> <%@, Taglib
Prefix= "S" uri= "/struts-tags"%>
<! DOCTYPE HTML PUBLIC "-//W3C//DTD XHTML 1.0 transitional//en" "Http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd ">
6. Configure 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>Upload</display-name> <filter> <FILTER-NAME>STRUTS2&L T;/filter-name> <filter-class>org.apache.struts2.dispatcher.ng.filter.strutsprepareandexecutefilter
</filter-class> <init-param> <param-name>actionPackages</param-name>
<param-value>com.figo.action</param-value> </init-param> </filter> <filter> <filter-name>struts-cleanup</filter-name> <filter-class> Org.apache.strut S2.dispatcher.ActionContextCleanUp </filter-class> </filter> <filter-mapping> <filter-name>struts-cleanup</filter-name> <url-p attern>/*</url-pattern> </filter-mapping> <filter-mapping> <filter-name>struts2</f ilter-name> <url-pattern>/*</url-pattern> </filter-mapping> <welcome-file-list> ;welcome-file>index.html</welcome-file> <welcome-file>index.htm</welcome-file> < Welcome-file>index.jsp</welcome-file> </welcome-file-list> </web-app>
The key is to add <init-param>,actionpackages as the package that contains the action file in the filter.
7. Page Test:
File Upload page:
File Upload return Result:
Because it was tested in Eclipse Engineering, the file was saved in a temporary file, and if it was really published, the uploaded file would be saved to the predefined directory.
Note:
1. struts2 default maximum can upload 2M file, can enlarge the default file upload size in struts.xml.
2. The summary of commonly used annotations is as follows:
Namespace: Specifies the namespace.
Parentpackage: Specifies the parent package.
Result: Provides a mapping of action results (a mapping of results).
Results: List of "result" annotations.
Resultpath: Specifies the base path of the resulting page.
Action: Specifies the access URL for the action.
Actions: List of "Action" annotations.
Exceptionmapping: Specifies an exception mapping (mapping a Declaration exception).
Exceptionmappings: An array of first-level declaration exceptions.
Interceptorref: Interceptor Reference.
Interceptorrefs: Interceptor Reference Group.
Here is just to give you a good effect, the program itself is very simple, mainly configuration, the next article 0 profile download.
Source code Download Link: http://download.csdn.net/detail/sxwyf248/4462899