1. Upload the file:
1). 3 points to note for the form
<%@ 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 "><HTML><Head><Metahttp-equiv= "Content-type"content= "text/html; charset=utf-8"><title>Insert Title here</title></Head><Body> <!--1,form Form Request if POST request 2,enctype= "Multipart/form-data" 3, Upload control <input type= "file" name= "file"/> - <formAction= "${pagecontext.request.contextpath}/fileuploadaction"Method= "POST"enctype= "Multipart/form-data">file 1:<inputtype= "File"name= "File" /><BR/>File 2:<inputtype= "File"name= "File" /><BR/> <inputtype= "Submit"value= "Upload file 2"> </form></Body></HTML>
2). Struts2 file upload is actually using the Commons FileUpload component, so you need to import
Commons-fileupload-1.3.jar
Commons-io-2.0.1.jar(Here the Fileutils CopyFile method under the jar package is used to convert the IO stream)
3). Struts2 file upload requires the use of FileUpload interceptors
4). Basic File Upload: Define the following 3 properties directly in the Action, and provide the corresponding getter and setter
Single File Upload:
File object corresponding to files
Private File [filefieldname];//Note that the name is identical to the name of <input type= "file" name= "file"/> Control
File type
Private String [filefieldname]contenttype;//control's name name +contenttype
Filename
Private String [filefieldname]filename;//control's name name +filename
If you are uploading multiple files:
A collection of file objects corresponding to the files
Private list<file> file;//Note that the name here is identical to the name of <input type= "file" name= "file"/> Control
File Type Collection
Private List<string> The name name of the filecontenttype;//control +contenttype
File Name Collection
Private List<string> The name name of the filefilename;//control +filename
5). Upload the file using IO stream.
Commons-io-2.0.1.jar (Here the Fileutils CopyFile method under the jar package is used to convert the IO stream)
6). What if I pass multiple files at once?
If you pass multiple files, the above 3 attributes can be changed to a List type! The name attribute values for multiple file domains need to be consistent.
Action Code:
Package Com.ibm.action;import Java.io.file;import Java.util.list;import org.apache.commons.io.fileutils;import Org.apache.struts2.servletactioncontext;import Org.apache.struts2.convention.annotation.action;import Org.apache.struts2.convention.annotation.namespace;import Org.apache.struts2.convention.annotation.parentpackage;import Org.apache.struts2.convention.annotation.Result; Import com.opensymphony.xwork2.actionsupport;/** * Description://Module purpose, Function description * * @author Administrator date:2018 Year March 10 * * @ParentPackage ("Struts-default") @Namespace ("/") public class Helloaction extends Actionsupport {private list<file > file;//Note the name here is the same as <input type= "file" name= "file"/> The name of the control is the same as the private list<string> filecontenttype;// control's name name +contenttype private list<string> filefilename;//control's name name +filenamepublic list<file> getFile () { return file;} public void Setfile (list<file> file) {this.file = file;} Public list<string> Getfilecontenttype () {return filecontenttype;} PubLIC void Setfilecontenttype (list<string> filecontenttype) {this.filecontenttype = Filecontenttype;} Public list<string> Getfilefilename () {return filefilename;} public void Setfilefilename (list<string> filefilename) {this.filefilename = Filefilename;} @Action (value = "Fileuploadaction", results = {@Result (name = "Success", location = "/web-inf/success.jsp")}) public Stri Ng FileUpLoad () throws Exception {System.out.println (file); System.out.println (Filecontenttype); System.out.println (filefilename);//For example: securecrt.rar//parameter: Web resource path return value the actual disk path after the item is published to the server string Filesrealpath = Servletactioncontext.getservletcontext (). Getrealpath ("/files"); for (int i = 0; i < file.size (); i++) {File DestFile = n EW file (Filesrealpath, Filefilename.get (i));//Parameter One: folder path, parameter two: file name, return file Object Fileutils.copyfile (File.get (i), destfile) ;//Parameter one: Original file object, parameter two: Target file object function, copy the contents of the original file object to the target file object
Note: This code some bugs, if the server's Files folder already has the same type of file, the upload will replace the previous content, so here to upload the file to set a new name, recommended Uuid}return SUCCESS;}}
7). Can I restrict the uploaded files? such as extension, content type, upload file size? If so, what error message will be displayed if there is an error? Can messages be customized?
OK!
There are two types of configurations:
Mode 1,struts.multipart.maxSize,(the total size of all files uploaded at one time, in bytes, global effect )
If not set , the STRUTS2 core package org.apache.struts2 under the default.properties file has the default size setting struts.multipart.maxsize=2097152 , that is, 2M. This is the first struts2 file upload, this configuration is a request can upload the total size of the file limit, that is, if a request to upload multiple files, multiple file size sum cannot exceed this setting.
You can modify the limit by using constants
struts.multipart.maxsize=2097152 2 megabytes (MB) = 2097152 bytes (b)
Mode 2,(the size of a single file that is requested to be uploaded one time, in bytes, applies to the local action , note: Not that this request can only upload a file, can be multiple, do not misunderstand, just no matter whether uploading one or more, The maximum size of each file is the value of this setting)
Can be limited by configuring the parameters of the Fileuploadinterceptor interceptor for file upload sizes for local action requests
MaximumSize (optional)-the maximum length (in bytes) to upload a single file, the default value is 2MB, that is, the default is a <input type= "file" name= "file"/> The maximum size of the file can be uploaded 2MB
Allowedtypes (optional)-the type of upload file allowed. Multiple use, Split (MIME type)
Allowedextensions (optional)-extension of the allowed upload file. Multiple use, split.
Example:
<!-- Global configuration: The total maximum size of the modified request upload file is 20M--><constant name= "struts.multipart.maxSize" value= "20971520" > </constant><package name= "Default" extends= "Struts-default" namespace= "/" ><interceptors>< Interceptor-stack name= "Atguigustack" ><interceptor-ref name= "Defaultstack" ><param name= " Fileupload.maximumsize ">12582912</param><!--to modify the size of a single file for a request upload of 12M--><!--<param name=" Fileupload.allowedtypes ">text/html,text/xml</param> <param name=" Fileupload.allowedextensions "> Html,dtd,xml</param>--></interceptor-ref></interceptor-stack></interceptors>< Default-interceptor-ref name= "Atguigustack" ></default-interceptor-ref></package>
Detailed: Original link, http://blog.csdn.net/moshenglv/article/details/51991197
Struts2 File Upload two restrictions , one is struts.multipart.maxSize, if not set , struts2 the core package under the The Default.properties file has a default size setting of struts.multipart.maxsize=2097152, which is 2M. This is the first pass of the struts2 file upload.
The second pass is the maximumsize in the Inteceptor . When the true file size can pass through the first pass . For inteceptor configured in different action , MaximumSize can play a corresponding interception role .
Like struts.multipart.maxsize=50m .
the maximumsize=30m of Inteceptora in Actiona
the maximumsize=10m of Inteceptorb in ACTIONB
struts.multipart.maxsize=50m for Inteceptora,b will play the first role .
Inteceptora and Inteceptorb can, after the first pass , tailor their respective operations to the interceptor according to their own business maximumsize
If the real file >50m. Throw will throw the request was rejected because its size (XXXX) exceeds the configured maximum (XXXX) exception, he is not is internationalized because this information is thrown by the Commons-fileupload component and is not supported by internationalization.
Source can see struts2.2 Org.apache.commons.fileupload.FileUploadBase.java
If Inteceptora uploads a real file of 40M
At this point, the Interceptor Inteceptora will access The internationalization information: struts.messages.error.file.too.larges corresponding value . When and only when uploading a file <=30m , the Inteceptora will not be uploaded successfully.
The following is an issue that addresses the struts.multipart.maxSize of information that is not friendly .
When more than 50M . Commons-fileupload throws a run-time exception
STRUTS2 will see this exception as an action-level exception . So the exception information
The request was rejected because its size (XXXX) exceeds the configured maximum (XXXX) is written into the actionerror.
All we need to do is overwrite the Addactionerror method in action.
@Override
Public void addactionerror (String anerrormessage)
{
To take value from internationalization.
If (Anerrormessage.startswith ("The request is rejected because its size")
{
Super. Addactionerror (GetText ("Struts.multipart.maxSize.limit"));
}
Else
{
Super. Addactionerror (Anerrormessage);
}
}
The corresponding configuration file
The struts.multipart.maxsize.limit= system uploads files up to 50M
struts.messages.error.file.too.larges= new ads Bulk upload files up to 5M
struts.messages.error.content.type.not.allowed= uploaded file formats currently only supported in XLS format
struts.messages.error.uploading= Upload file failed
Struts.messages.invalid.token= you have submitted the form, please do not repeat the submission.
Fileupload.filenums.exceed= already has more than 5 files running , please try again after a while
Filedownload.rows.exceed= because the number of ads in your ad group is too large, please download them in groups
Accountnotexist= customer does not exist
invalidtask= Invalid task
Note that the other textual content entered on the original page is missing because inteceptor midway back, meaning that the params injection failed.
Because this exception is captured before the file upload, the file is not uploaded, and the params is injected, so it is best to redirect to a jsp file, prompting the upload failed, and then rewrite to fill in the appropriate information.
Workaround : It is a good idea to skip to a page that specifically displays the error . Instead of returning to the action page.
Reference Links:
Https://www.cnblogs.com/biehongli/p/6509557.html
Struts2 File Upload