Struts2 implements the file upload function, and struts2 implements File Upload

Source: Internet
Author: User

Struts2 implements the file upload function, and struts2 implements File Upload

The HTTP servletrequest standard of Servlet 3.0 provides methods to process file uploads, but such uploads must be completed in Servlet. Struts2 provides simpler encapsulation.

Struts2 uses the File Upload framework of the Common-FileUpload of Jakarta by default, so to use the file upload function of Struts2, you need to add two jar packages, namely commons-io-2.2.jar and commons-fileupload-1.3.1.jar.

Example of Struts2 simple file upload:

1. File upload page

To upload files, the form method must be set to POST and enctype to multipart/form-data. Once the enctype is set to multipart/form-data, the browser uses a binary stream to process form data.

<% @ Taglib prefix = "s" uri = "/struts-tags" %> <% -- Created by IntelliJ IDEA. user: Administrator Date: 2018/1/16 Time: To change this template use File | Settings | File Templates. -- %> <% @ page contentType = "text/html; charset = UTF-8 "language =" java "%> 

2. Actions for processing upload requests

/*** Description: Struts2 simple File upload * Author: Eleven * Date: 2018/1/24 */public class FileAction extends ActionSupport {// upload the private File upload; // upload file type: private String uploadContentType; // Upload File Name: private String uploadFileName; // The type allowed for file upload is in struts. private String allowTypes; public String page () {return "page";} public void upload () {// file upload: // 1. read File Content // 2. write the file content to the specified file. try {Sy Stem. out. println ("File Upload allowed type =" + allowTypes); String realPath = ServletActionContext. getServletContext (). getRealPath ("/upload"); System. out. println ("absolute path of the project =" + realPath); // create a File to save the directory new File (realPath ). mkdir (); File file = new File (realPath + "/" + uploadFileName); // if (! File. exists () {file. createNewFile ();} FileOutputStream out = new FileOutputStream (file); FileInputStream in = new FileInputStream (upload); byte [] buffer = new byte [1024]; int len = 0; // read and write while reading 1 kb each time write 1 kb while (len = in. read (buffer)> 0) {out. write (buffer, 0, len);} System. out. println ("the file is uploaded successfully... ");} catch (Exception e) {e. printStackTrace () ;}} public File getUpload () {return upload;} public void setUpload (File upload) {this. upload = upload;} public String getUploadContentType () {return uploadContentType;} public void setUploadContentType (String uploadContentType) {this. uploadContentType = uploadContentType;} public String getUploadFileName () {return uploadFileName;} public void setUploadFileName (String uploadFileName) {this. uploadFileName = uploadFileName;} public String getAllowTypes () {return allowTypes;} public void setAllowTypes (String allowTypes) {this. allowTypes = allowTypes ;}}

If the form contains a file field whose name attribute is xxx, the corresponding Action needs to use three member variables to encapsulate the information of the file field.

The xxx member variable of the File type encapsulates the File content corresponding to the File domain.

The xxxFileName member variable of the String type encapsulates the file name corresponding to the file field.

The xxxContentType member variable of the String type encapsulates the file type of the file corresponding to the file field.

3. Configure struts. xml

<? 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 =" false "/> <constant name =" struts. devMode "value =" true "/> <package name =" default "namespace ="/"extends =" struts-default "> <! -- File Upload --> <action name = "file _ *" class = "eleven. action. <result name = "page">/WEB-INF/jsp/fileUpload. jsp </result> <! -- Dynamically set the action attribute. Here, we set the File Upload type, but the action program does not process too much --> <param name = "allowTypes"> image/png, image/gif, image/jpeg </param> </action> </package> </struts>

The interceptor implements file filtering.

Struts2 provides a file upload interceptor, fileUpload. To enable this Interceptor to take effect, configure the interceptor reference in the action.

When configuring the fileUpload interceptor, you can specify two parameters for it:

AllowTypes: Specifies the file type that can be uploaded. Multiple file types are separated by commas (,).

MaximumSize: the size of the file to be uploaded, in bytes.

When file filtering fails, the system automatically transfers the file to the input logic view. Therefore, you must configure the logic view named input for this Action. In addition, you must configure the ultstack interceptor reference for this Action.

The struts. xml configuration file is as follows:

<? 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 =" false "/> <constant name =" struts. devMode "value =" true "/> <package name =" default "namespace ="/"extends =" struts-default "> <! -- File Upload --> <action name = "file _ *" class = "eleven. action. FileAction" method = "{1}"> <! -- Configure the fileUpload interceptor before the ultstack interceptor Stack --> <interceptor-ref name = "fileUpload"> <! -- File types that can be uploaded --> <param name = "allowedTypes"> image/png, image/gif, image/jpeg </param> <! -- Size of the file to be uploaded --> <param name = "maximumSize"> 2000 </param> </interceptor-ref> <! -- Configure the system default interceptor --> <interceptor-ref name = "defaultStack"/> <! -- Configure the input view page --> <result name = "input">/WEB-INF/jsp/input. jsp </result> <result name = "page">/WEB-INF/jsp/fileUpload. jsp </result> </action> </package> </struts>

The file upload interceptor configured above requires that the file upload type be only image files, and the file size cannot exceed 2000 bytes. If the uploaded file is too large or the file type does not match, it will jump to the input logic view.

The above is all the content of this article. I hope it will be helpful for your learning and support for helping customers.

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.