Go to file upload in struts 2

Source: Internet
Author: User
Tags tmp folder

Some friends emailed me a while ago about how struts 2 uploads files, so today we will discuss this issue.

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 " %> <! 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 >     < s:form action ="fileUpload" method ="POST" enctype ="multipart/form-data" >         < s:file name ="myFile" label ="Image File" />         < s:textfield name ="caption" label ="Caption" />                < s:submit />     </ s:form > </ body > </ html >

Listing 2 fileupload. jsp

In fileupload. jsp, set the form submission method to post and enctype to multipart/form-data. Next, the <s: File/> flag binds the File Upload control to the myfile attribute of the action.

Followed by the fileuploadaction. Java code:

 
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 the file uploaded by the browser to the uploadimages folder of the Web application. The name of the new file is composed of the system time and the suffix of the uploaded file, this name will be assigned to the imagefilename attribute for redirect pages that are successfully uploaded.

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" >         < img src =‘UploadImages/<s:property value ="imageFileName" /> ‘ />        < 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 >

  

Listing 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 >

  

Listing 6. WEB-INF/Web. xml

Publish and run the application. In the address bar of the browser, enter http: // localhost: 8080/struts2_fileupload/fileupload. jsp. The following figure is displayed:

 
Listing 7 fileupload page

Select the image file, fill in the caption, and press the submit button to submit the file. The following figure is displayed:

 
Listing 8 successful upload page

More configurations

When running the above example, if you pay attention to it, you should find that the server console has the following output:

Mar 20 , 2007 4 : 08 : 43 PM org.apache.struts2.dispatcher.Dispatcher getSaveDirINFO: Unable to find ‘struts.multipart.saveDir‘ property setting. Defaulting to javax.servlet.context.tempdirMar 20 , 2007 4 : 08 : 43 PM org.apache.struts2.interceptor.FileUploadInterceptor interceptINFO: Removing file myFile C:\Program Files\Tomcat 5.5 \work\Catalina\localhost\Struts2_Fileupload\upload_251447c2_1116e355841__7ff7_00000006.tmp

  

List 9 server console output

The above information tells us that struts. multipart. savedir is not configured. Struts. multipart. savedir is used to specify the folder for storing temporary files. This configuration is written in the Struts. properties file. For example, if you add the following code to the Struts. properties file:

struts.multipart.saveDir = /tmp

  

Listing 10 struts Configuration

In this way, the uploaded file will be temporarily saved to the TMP folder under your root directory (generally c: \ TMP). If this folder does not exist, Struts 2 will automatically create one.

Error Handling

The image upload function is implemented in the preceding example. Therefore, users should be prevented from uploading non-image files. How can we achieve this in struts 2? In fact, this is also very simple. Just modify the above example as follows.

Modify fileupload. jsp and add "<s: fielderror/>" between <body> and <s: Form> to output error messages on the page.

Modify the Struts. xml file and change the definition of Action fileupload to the following:

 < action name ="fileUpload" class ="tutorial.FileUploadAction" >             < interceptor-ref name ="fileUpload" >                 < param name ="allowedTypes" >                     image/bmp,image/png,image/gif,image/jpeg                </ param >             </ interceptor-ref >             < interceptor-ref name ="defaultStack" />                        < result name ="input" > /FileUpload.jsp </ result >             < result name ="success" > /ShowUpload.jsp </ result >         </ action >

  

Configuration File Modified in listing 11

Obviously, the function is the allowtypes parameter of the fileupload interceptor. In addition, defaultstack is also introduced in the configuration, which will help us add verification and other functions. Therefore, after an error occurs, the system will jump to the result named "input", that is, fileupload. jsp.

Publish and run the application. When an error occurs, the page is shown in:

 
List 12 error prompt page

The error message above is the default value of struts 2. In most cases, we need to customize and internationalize this information. Add "struts. messages. error. content. type. not. allowed = the file you uploaded is not a image ", which can meet the requirements mentioned above. If you have any questions, please refer to my previous article "i18n your application in struts 2.0".

The error page after implementation is shown in:

 
Listing 13 custom error prompt page

In the same way, you can use the "maximumsize" parameter to limit the size of the uploaded file. Its character resource name is "struts. Messages. Error. file. Too. Large ".

When the character resource "struts. Messages. Error. Uploading" is used, a general upload error message is displayed.

Multi-File Upload

Similar to single-file upload, Struts 2 implements Multifile upload. You can bind multiple <s: File/> to an array or list of actions. As shown in the following example.

< s:form action ="doMultipleUploadUsingList" method ="POST" enctype ="multipart/form-data" >     < s:file label ="File (1)" name ="upload" />     < s:file label ="File (2)" name ="upload" />     < s:file label ="FIle (3)" name ="upload" />     < s:submit /> </ s:form >

  

Listing 14 JSP code snippets uploaded from multiple files

If you want to bind to an array, the Action Code should be similar:

 
    private File[] uploads;     private String[] uploadFileNames;     private String[] uploadContentTypes;     public File[] getUpload() { return this .uploads; }      public void setUpload(File[] upload) { this .uploads = upload; }       public String[] getUploadFileName() { return this .uploadFileNames; }      public void setUploadFileName(String[] uploadFileName) { this .uploadFileNames = uploadFileName; }       public String[] getUploadContentType() { return this .uploadContentTypes; }      public void setUploadContentType(String[] uploadContentType) { this .uploadContentTypes = uploadContentType; }

  

Listing 15 binding action code snippets to Multiple File Upload Arrays

If you want to bind to the list, it should be similar:

     private List < File > uploads = new ArrayList < File > ();     private List < String > uploadFileNames = new ArrayList < String > ();     private List < String > uploadContentTypes = new ArrayList < String > ();     public List < File > getUpload() {         return this .uploads;    }      public void setUpload(List < File > uploads) {         this .uploads = uploads;    }       public List < String > getUploadFileName() {         return this .uploadFileNames;    }      public void setUploadFileName(List < String > uploadFileNames) {         this .uploadFileNames = uploadFileNames;    }       public List < String > getUploadContentType() {         return this .uploadContentTypes;    }      public void setUploadContentType(List < String > contentTypes) {         this .uploadContentTypes = contentTypes;    }

  

Listing 16 binding action code snippets to The Multifile upload list

Summary

It is really easy to implement file upload in struts 2. All you need to do is bind the <s: File/> with the action attribute. This once again proves the ease of use of struts 2.

 

This article from: http://www.blogjava.net/max/archive/2007/03/21/105124.html

Go to file upload in struts 2

Related Article

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.