Struts (eight) file upload

Source: Internet
Author: User
Tags cos


File Upload Brief

Struts2 file uploads do not use the servlet 3.0 API, so struts2 file uploads also need to rely on common-fileupload, cos and other file upload components.

To be able to upload a file, you must set the form's method to post, set Enctype to Multipart/form-data, add < input type= "file" > field. In this way, the browser sends the binary data of the user's selected file to the server.

Set the enctype to Multipart/form-data, the browser will use the binary stream to process the form data, the Servlet 3.0 specification HttpServletRequest has provided a way to handle file uploads, But this upload needs to be done in the servlet, while the STRUTS2 provides a simpler package.

STRUTS2 does not provide its own request resolver, so struts2 does not handle multipart/form-data requests by itself, it needs to invoke other upload frameworks to parse the binary request data. But in the struts2 of the original upload parser to do further encapsulation, more simplified file upload.
Struts2 in the Struts.properties configuration file, see the following configuration code, which is primarily used to configure the upload parser when struts2 uploads a file.

#指定使用COS的文件上传解析器#struts.multipart.parser=cos#指定使用Pell的文件上传解析器#struts.multipart.parser=pell#struts2默认使用Jakarta的Common-FileUpload的文件上传解析器struts.multipart.parser=jakarta


The STRUTS2 package isolates the difference between the underlying file components, where developers can switch between different file upload frames by configuring the parser used for file uploads.

Struts2 uses Jakarta's Common-fileupload file upload framework by default, so if you need to use Struts's file upload feature, You will need to add the two jar packages of Commoms-io-2.2.jar and Commons-fileupload-1.3.1.jar to the Web app, and copy the two files under Struts2 project Lib to the Web-inf\lib path of the Web App.

Struts2 defaults to uploading files using Jakarta's Common-fileupload, because they are all items under Apache, but not necessarily only using Jakarta common-fileupload file uploads. You can also use the COS, Pell file upload support in your Web app. For developers, which file upload support to use, only need to modify the Struts.multipart.parse constant, and in the Web application to add the corresponding library to upload the project.

Struts2 file upload support in the original file project has been further encapsulated, simplified the file Upload code implementation, canceled the different upload project programming differences.

File Upload Implementation

The following is an example of struts2 default file upload support, using FileUpload interceptors and Jakarta Commons FileUpload components to complete file uploads.

Steps:
1. Use the file tag in the document upload form on the JSP page. If you need to upload multiple files at once, you must use multiple file tags, but their names must be the same
2. Add 3 new and file upload related properties to the Action. The names of these 3 properties must be in the following format
[File Name]: file-the document being uploaded. For example: Data
[File Name] Contenttype:string-The file type of the uploaded file. Example: Datacontenttype
[File Name] Filename:string-file name of the uploaded file. Example: DataFileName
If you upload more than one file, you can use List.

Suppose the File upload page as shown, which includes two form fields: text title and File field, in order to complete the file upload, it should be said that the two form fields with the Enctype property of the form is set to "Multipart/form-data".



The page code is as follows.

<%@ page contenttype="text/html; CHARSET=GBK " language=" java " errorpage="" %><% @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>Simple File Upload</title></head><body><s:form Action="Upload"enctype="Multipart/form-data" >        <s:textfield name="title" Label="file title"/>    <s:file name="Upload" label="Select File"/>    <s:submit value="Upload"/></s:form></body></html>


The above uses the STRUTS2 tag library to generate a form for uploading files, where < s:file.../> is used to generate a file upload domain. When the page submits the request, the request is sent to Upload.action, which is an action of struts2.

The action of the STRUTS2 is not responsible for handling the HttpServletRequest request, and the struts2 action is completely detached from the servlet API. The STRUTS2 framework is responsible for parsing the parameters in the HttpServletRequest request, including the file domain, struts2 using the file type to encapsulate the domain.

 Public  class uploadaction extends actionsupport{    //Encapsulates the properties of a file header request parameter    PrivateString title;//Encapsulate the properties of the uploaded file domain    PrivateFile upload;//Encapsulates the properties of the upload file type    PrivateString Uploadcontenttype;//Encapsulates the properties of the upload file name    PrivateString Uploadfilename;//Properties configured directly in the Struts.xml file    PrivateString Savepath;//Accept the Struts.xml file configuration value method     Public void Setsavepath(String value) { This. Savepath = value; }//Get the location where the uploaded files are saved    PrivateStringGetsavepath()throwsexception{returnServletactioncontext.getservletcontext (). Getrealpath (Savepath); }//Title Setter and getter method     Public void Settitle(String title) { This. title = title; } PublicStringGetTitle(){return( This. title); }//Upload setter and getter method     Public void Setupload(File upload) { This. upload = upload; } PublicFileGetupload(){return( This. upload); }//Uploadcontenttype Setter and getter Method     Public void Setuploadcontenttype(String Uploadcontenttype) { This. Uploadcontenttype = Uploadcontenttype; } PublicStringGetuploadcontenttype(){return( This. Uploadcontenttype); }//Uploadfilename Setter and getter Method     Public void Setuploadfilename(String uploadfilename) { This. uploadfilename = Uploadfilename; } PublicStringGetuploadfilename(){return( This. uploadfilename); }@Override     PublicStringExecute()throwsexception{//Create an upload file output stream with the server's file save address and the original file nameFileOutputStream fos =NewFileOutputStream (Getsavepath () +"\\"+ Getuploadfilename ()); FileInputStream FIS =NewFileInputStream (Getupload ());byte[] buffer =New byte[1024x768];intLen =0; while(len = fis.read (buffer)) >0) {fos.write (buffer,0, Len); } fos.close ();returnSUCCESS; }}


The action here is similar to the general action, providing the upload and title two member variables corresponding to the Name property of the two form fields, which encapsulate the request parameters for two form fields.

In addition, the action contains the Uploadfilename and uploadcontenttype two member variables that encapsulate the file name of the uploaded file and the type of files that are uploaded. The action class directly encapsulates the file contents of the uploaded file directly through the file Type property, but this file property cannot get the file name and file type of the uploaded files. So struts2 encapsulates the file name and file type information contained in the domain into the uploadname and Uploadcontenttype member variables. It can be understood that if the form contains a file field with the name attribute xxx, the corresponding action requires three member variables to encapsulate the information for that file field. The

> XXX member variable of type file encapsulates the file contents for that file field. The

> Xxxfilename member variable of type string encapsulates the file name of the file that corresponds to the file field. The

> Xxxcontenttype member variable of type string encapsulates the file type of the file that corresponds to the file field.

with the above three member variables, you can simply implement the file upload, all in the Execute () method, you can directly call the GetXXX () method to get the file name, file type, and file contents.

Additionally, the above action contains a SAVEPATH member variable that is set by the configuration file, allowing the value of the member variable to be set dynamically. The properties in the action of the

Struts2, in addition to encapsulating the HTTP request parameters, can encapsulate the results of the action and accept the injection of the STRUTS2 framework by configuring it in the Struts2 configuration file. Allows the property to be specified dynamically in the configuration file. The configuration of the action that the

file uploads

The struts2 file uploads an action that is similar to the configuration of the normal action, specifying the name of the action, and the implementation class for the action, as well as the action configuration < result.../> elements. The difference is that the action also configures a < Param.../>, which is used to dynamically assign property values to the action's properties.

<?xml version= "1.0" encoding= "GBK"?><! DOCTYPE struts Public "-//apache software foundation//dtd struts Configuration 2.3//en" "Http://struts.apache.org/dt Ds/struts-2.3.dtd "> <struts>    <!--Set the character set used by the app--    <constant name="struts.i18n.encoding" value="GBK"/>     < package name="Lee" extends= "struts-default">         <!--Configure the action to process file uploads--        <action name="Upload" class="Org.crazyit.app.action.UploadAction" >            <!--dynamically set the property value of action--            <param name="Savepath">/uploadfiles</param>            <!--Configure Struts 2 default view page--            <result>/web-inf/content/succ.jsp</result>          </Action>        <action name="*">            <result>/web-inf/content/{1}.jsp</result>           </Action>    </Package ></struts>


After configuring the Web app, if you enter the file title in the form page and browse for the file you want to upload, and then click the Upload button, the request will be uploadaction processed, processed and transferred to the Succ.jsp page, which uses a simple struts2 tag to display the uploaded image. The code for the Succ.jsp page is as follows.

<%@ page contenttype="text/html; CHARSET=GBK " language=" java " errorpage="" %><% @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>Upload successful</title></head><body>Upload success!<br/>File title:<s:property value="+ title"/><br/>Files are:<img src="<s:property value="' uploadfiles/' + UPLOADFI Lename"/>"/><br/></body></html>


The file name is still unchanged when you save the file to the server when the above example uploads. In the actual project, it is generally recommended to use the Java.util.UUID tool class to generate a unique file name because of the same file name that may occur when multiple users upload concurrently.

Visible STRUTS2 Implementation of the file upload is very simple, as long as the file domain and the action in a type of File member variable association, you can easily access to upload the file content.

Struts2 the key to implementing file uploads is to use three member variables to encapsulate the file domain, respectively, to encapsulate the file name, the file type, and the file contents of the file.

Struts (eight) file upload

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.