Struts 2 uploads files

Source: Internet
Author: User
Tags i18n

The web is often used for file upload and download. In most cases, the user's request parameter on the form is a string, but if you set the form element to the "multipart/form-data" attribute, when a form is submitted, parameters are no longer submitted in the form of strings, but requests are submitted in binary format.

Enctype has the following attributes: application/x-www-form-urlencoded (default encoding, which processes only the value attribute values and URL encoding ); multipart/form-data (Processing form data using a binary stream will encapsulate the content of the file specified in the file field into the request parameters; the request cannot be used. getParameter method to obtain Request Parameters); text/plain (mainly used for Form Direct Mail ).

The upload framework is used to complete the upload. For java files, there are two Common upload frameworks: Common-FileUpload and COS, it is responsible for parsing all the fields in the HttpServletRequest request-whether it is a file field or a common form field.

Struts 2 File Upload

Struts 2 does not provide its own request parser. That is to say, struts 2 does not process multipart/form-data requests by itself. It needs to call other upload frameworks to parse binary request data. Struts 2 is further encapsulated on the basis of the original upload parser to further simplify file upload.

For example, upload an object.

The Code is as follows:

<Body> <form action = "upload. action "method =" post "enctype =" multipart/form-data "> file title: <input type = "text" name = "title"/> <br/> select a file: <input type = "file" name = "upload"/> <br/> <input value = "upload" type = "submit"/> </form> </body>

The Action of Struts 2 does not need to process the HttpServletRequest request. As described above, the Action of Struts 2 has been completely separated from the Servlet API. The Struts 2 framework is responsible for parsing parameters in the HttpServletRequest request, including File fields. Struts 2 uses the File type to encapsulate File fields. The following is the Action for processing the upload request:

UploadAction. java

Package Lee; import COM. opensymphony. xwork2.action; import Org. apache. struts2.servletactioncontext; import Java. io. file; import Java. io. *; import COM. opensymphony. xwork2.actionsupport; public class uploadaction extends actionsupport {// encapsulate the attribute private String title of the file title request parameter; // encapsulate the attribute private file upload of the uploaded file domain; // encapsulate the private string uploadcontenttype attribute of the upload file type; // encapsulate the private string uploadfilename attribute of the Upload File Name; // directly in struts. the attribute private string savepath configured in the XML file; // accept struts. XML file configuration value method public void setsavepath (string value) {This. savepath = value;} // returns the storage location of the uploaded file. Private string getsavepath () throws exception {return servletactioncontext. getrequest (). getrealpath (savepath);} // setter and getter methods of the file title Public void settitle (String title) {This. title = title;} Public String gettitle () {return (this. title);} // setter and getter methods of the file content corresponding to the uploaded file public void setupload (File Upload) {This. upload = upload;} public file getupload () {return (this. upload);} // setter and getter methods of the file type to be uploaded public void setuploadcontenttype (string uploadcontenttype) {This. uploadcontenttype = uploadcontenttype;} Public String getuploadcontenttype () {return (this. uploadcontenttype);} // setter and getter methods of the file name to be uploaded public void setuploadfilename (string uploadfilename) {This. uploadfilename = uploadfilename;} Public String getuploadfilename () {return (this. uploadfilename) ;}@ overridepublic string execute () throws exception {// create an upload file output stream fileoutputstream Fos = new fileoutputstream (getsavepath () with the server's file storage address and original file name () + "\" + getuploadfilename (); fileinputstream FCM = new fileinputstream (getupload (); byte [] buffer = new byte [1024]; int Len = 0; while (LEN = FCM. read (buffer)> 0) {FOS. write (buffer, 0, Len);} return success ;}}

Corresponding Struts. xml

 

<? Xml version = "1.0" encoding = "GBK"?> <! DOCTYPE struts PUBLIC "-// Apache Software Foundation // DTD Struts Configuration 2.1 // EN" "http://struts.apache.org/dtds/struts-2.1.dtd"> <struts> <! -- Specify the baseName of the international resource file as globalMessages --> <constant name = "struts. custom. i18n. resources" value = "globalMessages"/> <! -- Set the decoding set used by the Application --> <constant name = "struts. i18n. encoding "value =" GBK "/> <constant name =" struts. multipart. saveDir "value ="/tmp "/> <package name =" lee "extends =" struts-default "> <! -- Configure the Action for processing file uploads --> <action name = "upload" class = "lee. UploadAction"> <! -- Dynamically set the Action property value --> <param name = "savePath">/upload </param> <! -- Configure the default view page of Struts 2 --> <result>/succ. jsp </result> </action> <action name = ""> <result>. </result> </action> </package> </struts>

Succ. jsp

<Body> upload successful! <Br/> file title: <s: property value = "+ title"/> <br/> file:  "/> <br/> </body>

 

Interface:

Struts can use list or array to upload multiple files:

  • Use array:
    Upload page:
<Form action = "upload. action "method =" post "enctype =" multipart/form-data "> file title: <input type = "text" name = "title"/> <br/> select the first file: <input type = "file" name = "upload"/> <br/> select the second file: <input type = "file" name = "upload"/> <br/> select the third file: <input type = "file" name = "upload"/> <br/> <input value = "upload" type = "submit"/> </form>

Action:

Public class uploadaction extends actionsupport {private String title; // use the File array to encapsulate the file content private file [] upload corresponding to multiple file domains; // use a string array to encapsulate the file type private string [] uploadcontenttype corresponding to multiple file domains; // use a string array to encapsulate the file name private string [] uploadfilename corresponding to multiple file domains; // Private string savepath, which accepts dependency injection; // setter and getter methods of the title attribute public void settitle (String title) {This. title = title;} Public String gettitle () {return this. title;} // setter and getter methods of the upload attribute public void setupload (file [] upload) {This. upload = upload;} public file [] getupload () {return this. upload;} // setter and getter methods of the uploadcontenttype attribute public void setuploadcontenttype (string [] uploadcontenttype) {This. uploadcontenttype = uploadcontenttype;} Public String [] getuploadcontenttype () {return this. uploadcontenttype;} // The setter and getter methods of the uploadfilename attribute are public void setuploadfilename (string [] uploadfilename) {This. uploadfilename = uploadfilename;} Public String [] getuploadfilename () {return this. uploadfilename;} // setter and getter methods of the savepath attribute public void setsavepath (string savepath) {This. savepath = savepath;} Public String getsavepath () {return servletactioncontext. getrequest (). getrealpath (savepath) ;}@ overridepublic string execute () throws exception {// get the file array to be uploaded file [] files = getupload (); // traverse each file to be uploaded for (INT I = 0; I <files. length; I ++) {// create an upload file output stream fileoutputstream Fos = new fileoutputstream (getsavepath () at the server's file storage address and original file name () + "\" + getuploadfilename () [I]); // create a file input stream fileinputstream (New fileinputstream (files [I]) for each file to be uploaded. // write each file to the corresponding file on the server. byte [] buffer = new byte [1024]; int Len = 0; while (LEN = FCM. read (buffer)> 0) {FOS. write (buffer, 0, Len);} FOS. close () ;}return success ;}}

 

The list method is similar.

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.