STRUTS2 series: (11) File upload

Source: Internet
Author: User
Tags i18n

Life gives us a huge and infinite noble gift, this is youth: full of strength, full of expectations, full of knowledge, full of hope.


Struts 2 uses FileUpload interceptors and Commons FileUpload components for file uploads.

Fileuploadinterceptor Full Name: Org.apache.struts2.interceptor.fileuploadinterceptorinterceptor that is  based off (based on)  of MultiPartRequestWrapper, which is automatically  Applied for any request that includes a file. it adds the  following parameters, where [File Name] is the name given  to the file uploaded by the html form: [file name] :  File - the actual file [file name]contenttype : string - the  content type of the file [file name]filename : string -  the actual name of the file uploaded  (not the html  Name)  you can get access to these files by merely providing  setters in your&nBsp;action that correspond to any of the three patterns above,  such as setdocument (file document),  setdocumentcontenttype (String contentType),  etc.



To upload a file using an HTML form in a JSP, you must set the Enctype property of the HTML form to Multipart/form-data and the method property to post. The HTML form contains the <input type= "file" > enables the user to choose to upload the file.


Basic steps:

1. The JSP page uses the file control in the form. If multiple file controls are required to be uploaded at one time, the Name property of the control must be the same


2. Action to add three file upload related properties.

Upload a single file property format

Attribute one: Type is file, name is page file control name

Attribute two: Type is string, name is page file control name +contenttype

Attribute three: Type is string, name is page file control name +filename

Upload multiple file attribute formats

Just replace the attribute type with an array or list.


1. Single File Upload

1.1. Steps to upload a single file

A) Add Jar package

b) Build Page

c) Create action

d) Configuration validation error jump page <result name= "input" >/upload/error.jsp</result>.


A) Add Jar package

Add Commons-fileupload.jar, Commons-io.jar

b) Build Page singlefile.jsp

<%@ page language= "java" contenttype= "text/html; Charset=utf-8 "pageencoding=" UTF-8 "%><! DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en" "Http://www.w3.org/TR/html4/loose.dtd" >

c) Create action

package com.rk.strut.f_fileupload;import java.io.file;import org.apache.commons.io.fileutils; Import org.apache.struts2.servletactioncontext;import com.opensymphony.xwork2.actionsupport;public  class singlefileupload extends actionsupport{private file uploadfile;private  String uploadFileContentType;private String uploadFileFileName;public void  Setuploadfile (file uploadfile) {this.uploadfile = uploadfile;} Public void setuploadfilecontenttype (string uploadfilecontenttype) {This.uploadFileContentType  = uploadfilecontenttype;} Public void setuploadfilefilename (string uploadfilefilename) {this.uploadfilefilename =  uploadfilefilename;} @Overridepublic  string execute ()  throws exception{system.out.println (uploadfilecontenttype ); String realpath = servletactioncontext.getservletcontext (). Getrealpath ("/uploadfiles"); file&Nbsp;folder = new file (Realpath); if (folder.exists ()  == false) {folder.mkdirs ();} File destfile = new file (Folder,uploadfilefilename); Fileutils.copyfile (Uploadfile, destfile);return  "Success";}}


d) Configuration validation error jump page <result name= "input" >/upload/error.jsp</result>.

Configuration in the Struts.xml

<package name= "Fileuploadpackage" namespace= "/rk/fileupload" extends= "Struts-default" > <action name= "Singl Efileupload "class=" com.rk.strut.f_fileupload.  Singlefileupload "> <result name=" Success ">/fileupload/success.jsp</result> <result Name= "Input" >/fileupload/error.jsp</result> </action> </package>

error.jsp

<%@ page language= "java" contenttype= "text/html; Charset=utf-8 "pageencoding=" UTF-8 "%><% @taglib uri="/struts-tags "prefix=" s "%><! DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en" "Http://www.w3.org/TR/html4/loose.dtd" >


1.2. Errors that may occur during the upload process

A) When uploading a file that exceeds 2MB, the following error message appears in the console of MyEclipse:

Warning: request exceeded size limit!org.apache.commons.fileupload.fileuploadbase$sizelimitexceededexception:the request was rejected because its size (4411489) exceeds the configured maximum (2097152)

At the very beginning of the article, the process of "Struts 2 using FileUpload interceptors and Commons FileUpload components for file uploads" is as follows:

1th, the file uploads the file to the server's Temp folder with the Commons FileUpload component.

The 2nd step, upload the successful file in the temporary folder and then filter by the FileUpload interceptor, if it complies with the conditions of the FileUpload interceptor, it will be formally saved to disk.

650) this.width=650; "src=" Http://s2.51cto.com/wyfs02/M02/83/2A/wKioL1dsN9bQScvhAAA-PtZqsvw452.png "title=" File upload. PNG "alt=" Wkiol1dsn9bqscvhaaa-ptzqsvw452.png "/>

This is equivalent to two doors, only through the two doors, can be counted as upload success!

The error just now was caused by the door of the Commons FileUpload component, in Struts2-core-2.jar's org/apache/ Struts2 folder has a default.properties file, which defines a constant: (2097152 = 2*1024*1024, the following 2097152 is the calculated unit is byte, exactly 2MB. )

struts.multipart.maxsize=2097152

This value limits the size of the upload file for the Commons FileUpload component.

The workaround is to modify this constant value in the Struts.xml file: (52428800 = 50*1024*1024,50MB)

<constant name= "struts.multipart.maxSize" value= "52428800"/>


1.3. limit file upload size and type with FileUpload interceptor


The FileUpload interceptor is responsible for handling file upload operations and is a member of the default Defaultstack interceptor stack.


The FileUpload Interceptor has 3 properties that can be set.

MaximumSize: Maximum length (in bytes) of the uploaded file, the default value is 2 MB

Allowedtypes: The type of file that is allowed to be uploaded, separated by commas between each type

Allowedextensions: Allow file extensions to be uploaded, separated by commas between extensions


Interceptor Parameters:

MaximumSize (optional)-The maximum size (in bytes), the interceptor would allow a file reference to is set on the action. Note, this is not a related to the various properties found in Struts.properties. Default to approximately 2MB.

Allowedtypes (optional)-a comma separated list of content types (ie:text/html) that the interceptor would allow a file reference to B E set on the action. If None is specified allow all types to be uploaded.

allowedextensions (optional)-a comma separated list of file extensions (ie:. html) that the interceptor would allow a file reference to be Set on the action. If None is specified allow all extensions to be uploaded.


To configure the FileUpload interceptor in action:

<action .....> <interceptor-ref name= "Defaultstack" > <param name= "fileupload.maximumsize" >4097 152</param> <param name= "Fileupload.allowedtypes" >application/msword,application/vnd.ms-excel</ param> <param name= "fileupload.allowedextensions" >.doc,.docx,.xls,.pdf</param> </interceptor-r Ef> .....</action>


Here's a comparison of two parameters:struts.multipart.maxSize and fileupload.maximusize

In section 1.2, we talked about uploading files in Struts2 through two doors: Commons FileUpload components and FileUpload interceptors. The Commons FileUpload component is the first door, and its corresponding parameter is struts.multipart.maxSize; The FileUpload interceptor is the second door, and its corresponding parameter is Fileupload.maximusize. Fileupload.maximusize should be less than struts.multipart.maxSize is reasonable.


Why do you want to set a value of two?

One advantage of this is that struts.multipart.maxSize can do a total file size control, and each action interceptor can set its own control file size. For example, when uploading an attachment, you can limit the file to less than 10MB, and when uploading a photo, you can limit the image to less than 1MB.


1.4. Further explanation of the allowedtypes and allowedextensions of the FileUpload interceptor

Someone has encountered a problem with file type filtering, and when both Allowedtypes and allowedextensions are set, some type of file may appear that cannot be uploaded.


Someone on the internet has made the following explanation:


Use one of the file type and file suffix names to control the type/suffix name of the uploaded file. However, the priority level of allowedtypes is higher than allowedextensions.

If Allowedtypes is configured, Allowedextensions will no longer take effect.

You cannot configure the Allowedtypes parameter by using the Allowedextensions parameter to control the suffix name of the uploaded file.

Otherwise, if the Allowedtypes parameter is configured, then the Allowedextensions parameter will no longer work.


Set up to use only the Allowedextensions parameter


1.5. Error handling of uploading files

It's all about how files are uploaded, how to configure FileUpload interceptors to limit file size and type.

However, when the uploaded file does not conform to the file size and type of the FileUpload interceptor limit, an error occurs and we should display this information to the user, so we configure the struts.xml in the action tag

<result name= "Input" >/upload/error.jsp</result>

When an error occurs, jump to the error.jsp page, and in error.jsp need to introduce a tag library

<% @taglib uri= "/struts-tags" prefix= "s"%>

The error message can be displayed through <s:fielderror/> on the page.

Error condition:

File size is very long

File type does not conform to allowedtypes, allowedextensions parameter requirements


Mode one: Direct use of the Struts-messages.properties file

The Struts-messages.properties file (under the ORG.APACHE.STRUTS2 package in struts2-core-2.x.x.x) is a predefined error message.

Struts.messages.error.uploading=error uploading: {0}struts.messages.error.file.too.large=file too large: {0} ' {1} ' ' { 2} "{3}struts.messages.error.content.type.not.allowed=content-type not allowed: {0}" {1} "" {2} "{3} Struts.messages.error.file.extension.not.allowed=file extension not allowed: {0} ' {1} ' ' {2} ' {3}

{0}: Upload Control name (file control name)

{1}: Upload file name

{2}: Upload temp directory name

{3}: Upload file type (if Struts.messages.error.file.too.large, the size of the uploaded file)


This interceptor would add several field errors, assuming that the action implements Validationaware. These error messages is based on several i18n values stored in struts-messages.properties, a default i18n file processed For all i18n requests. You can override the text of these messages by providing text for the following keys:


Struts.messages.error.uploading-a General Error This occurs when the file could is not being uploaded


Struts.messages.error.file.too.large-occurs when the uploaded file is too large


Struts.messages.error.content.type.not.allowed-occurs when the uploaded file does not match the expected content types s Pecified


Struts.messages.error.file.extension.not.allowed-occurs when the uploaded file does not match the expected file Extensio NS specified



Mode two: Define the properties file


The first step: Create a resource file, put it under SRC, and add the relevant information

Example: Fileuploadresource.properties

STRUTS.MESSAGES.ERROR.UPLOADING=\U6587\U4EF6\U4E0A\U4F20\U9519\U8BEF: {0}struts.messages.error.file.too.large=\ u6587\u4ef6\u592a\u5927: {0} "{1}" "{2}" {3}struts.messages.error.content.type.not.allowed=content-type\u4e0d\ U5141\U8BB8: {0} "{1}" "{2}" {3}struts.messages.error.file.extension.not.allowed=\u6269\u5c55\u540d\u4e0d\u5141\ U8bb8\: {0} "{1}"


Step Two: Load the resource file in the Struts.xml file

<constant name= "struts.custom.i18n.resources" value= "Fileuploadresource"/>




2. Upload Multiple Files


multifile.jsp

<%@ page language= "java" contenttype= "text/html; Charset=utf-8 "pageencoding=" UTF-8 "%><! DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en" "Http://www.w3.org/TR/html4/loose.dtd" >

Multifileupload.java

package com.rk.strut.f_fileupload;import java.io.file;import org.apache.commons.io.fileutils; Import org.apache.struts2.servletactioncontext;import com.opensymphony.xwork2.actionsupport;public  class multifileupload extends actionsupport{private file[] uploadfile;private  String[] uploadFileContentType;private String[] uploadFileFileName;public void  Setuploadfile (file[] uploadfile) {this.uploadfile = uploadfile;} Public void setuploadfilecontenttype (string[] uploadfilecontenttype) {This.uploadFileContentType  = uploadfilecontenttype;} Public void setuploadfilefilename (string[] uploadfilefilename) {this.uploadFileFileName =  uploadfilefilename;} @Overridepublic  string execute ()  throws Exception{String basePath =  Servletactioncontext.getservletcontext (). Getrealpath ("/uploadfiles"); File folder = new&nbsP File (BasePath); if (folder.exists ()  == false) {folder.mkdirs ();} if (uploadfile != null && uploadfile.length>0) {for (int i=0;i< uploadfile.length;i++) {file destfile = new file (folder,uploadfilefilename[i]); Fileutils.copyfile (Uploadfile[i], destfile);}} return  "Success";}}







STRUTS2 series: (11) File upload

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.