Implement file upload in struts2 (1)

Source: Internet
Author: User

Implementation Principle
Struts 2 is uploaded through the commons fileupload file. Commons fileupload saves HTTP data to a temporary folder, and Struts uses the fileupload Interceptor to bind the file to the action instance. So that we can operate the files uploaded by the browser in the form of local files.

Implementation
Some time ago, Apache released struts 2.0.6 ga. Therefore, this version of Struts is used as the framework. The following is a list of dependent class packages:

 
List 1 List of dependent class packages

First, create the file upload page fileupload. jsp with the following content:

<% @ Page Language = "Java" contenttype = "text/html; charset = UTF-8" pageencoding = "UTF-8" %>
<% @ Taglib prefix = "S" uri = "/Struts-tags" %>




struts 2 File Upload








List 2 fileupload. JSP
In fileupload. in JSP, set the form submission method to post and enctype to multipart/form-data, which is nothing special. Next, the flag binds the File Upload control to the myfile attribute of the action.

Followed by fileuploadaction. JavaCode:

Package tutorial;

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 java. util. date;

Import org. Apache. struts2.servletactioncontext;

Import com. opensymphony. xwork2.actionsupport;

Public class fileuploadaction extends actionsupport {
Private Static final long serialversionuid = 572146812454l;
Private Static final int buffer_size = 16*1024;

Private file myfile;
Private string contenttype;
Private string filename;
Private string imagefilename;
Private string Caption;

Public void setmyfilecontenttype (string contenttype ){
This. contenttype = contenttype;
}

Public void setmyfilefilename (string filename ){
This. filename = filename;
}

Public void setmyfile (File myfile ){
This. myfile = myfile;
}

Public String getimagefilename (){
Return imagefilename;
}

Public String getcaption (){
Return Caption;
}

Public void setcaption (string Caption ){
This. Caption = Caption;
}

Private Static 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 ();
}
}
} Catch (exception e ){
E. printstacktrace ();
}
}

Private Static string getextention (string filename ){
Int Pos = filename. lastindexof (".");
Return filename. substring (POS );
}

@ Override
Public String execute (){
Imagefilename = new date (). gettime () + getextention (filename );
File imagefile = new file (servletactioncontext. getservletcontext (). getrealpath ("/uploadimages") + "/" + imagefilename );
Copy (myfile, imagefile );
Return success;
}

} Listing 3 tutorial/fileuploadaction. Java
In fileuploadaction, I wrote four setter Methods: setmyfilecontenttype, setmyfilefilename, setmyfile, and setcaption. The latter two methods are easy to understand and correspond to fileupload. <s: File/> and <s: textfield/> in JSP. But the first two are not explicitly bound to any page sign, so where does their value come from? In fact, the <s: File/> flag is not only bound to myfile, but also myfilecontenttype (MIME type of the uploaded file) and myfilefilename (File Name of the uploaded file, this file name does not include the file path ). Therefore, <s: file name = "XXX"/> corresponds to the XXX, xxxcontenttype, and xxxfilename attributes in the action class.

Fileuploadaction is used to copy files uploaded by the browser to the Web application.ProgramIn the uploadimages folder of, the name of the new file is composed of the system time and the suffix of the uploaded file. The name will be assigned to the imagefilename attribute for redirect pages that are uploaded successfully.

Next we will look at the successful upload page:

<% @ 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">
<HTML xmlns = "http://www.w3.org/1999/xhtml">
<Head>
<Title> struts 2 File Upload </title>
</Head>
<Body>
<Div style = "padding: 3px; Border: solid 1px # cccccc; text-align: Center">
'/>
<Br/>
<S: property value = "caption"/>
</Div>
</Body>
</Html> listing 4 showupload. jsp
Showupload. jsp obtains the imagefilename and combines its uploadimages into a URL to display the uploaded image.

Then there is the action configuration file:

<? 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>
<Package name = "fileuploaddemo" extends = "struts-Default">
<Action name = "fileupload" class = "tutorial. fileuploadaction">
<Interceptor-ref name = "fileuploadstack"/>
<Result name = "success">/showupload. jsp </result>
</Action>
</Package>
</Struts> List 5 struts. xml
The fileupload Action explicitly applies the fileuploadstack interceptor.

Finally, the Web. xml configuration file:

<? XML version = "1.0" encoding = "UTF-8"?>
<Web-app id = "webapp_9" version = "2.4"
Xmlns = "http://java.sun.com/xml/ns/j2ee"
Xmlns: xsi = "http://www.w3.org/2001/XMLSchema-instance"
Xsi: schemalocation = "http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">

<Display-Name> struts 2 fileupload </display-Name>

<Filter>
<Filter-Name> Struts-cleanup </filter-Name>
<Filter-class>
Org. Apache. struts2.dispatcher. actioncontextcleanup
</Filter-class>
</Filter>

<Filter>
<Filter-Name> struts2 </filter-Name>
<Filter-class>
Org. Apache. struts2.dispatcher. filterdispatcher
</Filter-class>
</Filter>

<Filter-mapping>
<Filter-Name> Struts-cleanup </filter-Name>
<URL-pattern>/* </url-pattern>
</Filter-mapping>

<Filter-mapping>
<Filter-Name> struts2 </filter-Name>
<URL-pattern>/* </url-pattern>
</Filter-mapping>

<Welcome-file-List>
<Welcome-File> index.html </welcome-File>
</Welcome-file-List>

</Web-app>

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.