Вы находитесь на странице: 1из 11

4/22/2015

FileUploadApacheStruts2DocumentationApacheSoftwareFoundation

Pages / / Interceptors

FileUpload
AddedbyMatthieuChaseHeimer,lasteditedbyLukaszLenartonJul20,2014

TheStruts2frameworkprovidesbuiltinsupportforprocessingfileuploadsthatconformtoRFC1867,
"FormbasedFileUploadinHTML".Whencorrectlyconfiguredtheframeworkwillpassuploadedfile(s)into
yourActionclass.Supportforindividualandmultiplefileuploadsareprovided.Whenafileisuploadeditwill
typicallybestoredinatemporarydirectory.UploadedfilesshouldbeprocessedormovedbyyourAction
classtoensurethedataisnotlost.Beawarethatserversmayhaveasecuritypolicyinplacethatprohibits
youfromwritingtodirectoriesotherthanthetemporarydirectoryandthedirectoriesthatbelongtoyourweb
application.
Dependencies
BasicUsage
UploadingMultipleFiles
UploadingMultipleFilesusingArrays
UploadingMultipleFilesusingLists
AdvancedConfiguration
FileSizeLimits
FileTypes
ErrorMessages
TemporaryDirectories
AlternateLibraries

Dependencies
TheStruts2frameworkleveragesaddonlibrariestohandletheparsingofuploadedfiles.Theselibrariesare
notincludedintheStrutsdistribution,youmustaddthemintoyourproject.Thelibrariesneededare:
Library

URL

Struts2.0.x

Struts2.1.x

CommonsFileUpload

http://commons.apache.org/fileupload/

1.1.1

1.2.1

CommonsIO

http://commons.apache.org/io/

1.0

1.3.2

IfyouareusingMaventhenyoucanaddtheselibrariesasdependenciesinyourproject'spom.xml.
Struts2.0.xFileUploadDependencies
<dependency>
<groupId>commonsfileupload</groupId>
<artifactId>commonsfileupload</artifactId>
<version>1.1.1</version>
</dependency>
<dependency>
<groupId>commonsio</groupId>
https://cwiki.apache.org/confluence/display/WW/File+Upload

1/11

4/22/2015

FileUploadApacheStruts2DocumentationApacheSoftwareFoundation

<artifactId>commonsio</artifactId>
<version>1.0</version>
</dependency>

Struts2.1.xFileUploadDependencies
<dependency>
<groupId>commonsfileupload</groupId>
<artifactId>commonsfileupload</artifactId>
<version>1.2.1</version>
</dependency>
<dependency>
<groupId>commonsio</groupId>
<artifactId>commonsio</artifactId>
<version>1.3.2</version>
</dependency>

BasicUsage
Theorg.apache.struts2.interceptor.FileUploadInterceptorclassisincludedaspartofthe
defaultStack.Aslongastherequiredlibrariesareaddedtoyourprojectyouwillbeabletotakeadvantage
ofoftheStruts2fileUploadcapability.ConfigureanActionmappingforyourActionclassasyoutypically
would.
Exampleactionmapping:
<actionname="doUpload"class="com.example.UploadAction">
<resultname="success">good_result.jsp</result>
</action>
Aformmustbecreatewithaformfieldoftypefile,<INPUTtype="file"name="upload">.Theformusedto
uploadthefilemusthaveitsencodingtypesettomultipart/formdata,<FORMaction="doUpload"
enctype="multipart/formdata"method="post">.Thestandardprocedureforaddingtheseelementsis
byusingtheStruts2taglibrariesasshowninthefollowingexample:
ExampleJSPformtags:
<s:formaction="doUpload"method="post"enctype="multipart/formdata">
<s:filename="upload"label="File"/>
<s:submit/>
</s:form>
ThefileUploadinterceptorwillusesetterinjectiontoinserttheuploadedfileandrelateddataintoyourAction
https://cwiki.apache.org/confluence/display/WW/File+Upload

2/11

4/22/2015

FileUploadApacheStruts2DocumentationApacheSoftwareFoundation

class.Foraformfieldnameduploadyouwouldprovidethethreesettermethodsshowninthefollowing
example:
ExampleActionclass:
packagecom.example;

importjava.io.File;
importcom.opensymphony.xwork2.ActionSupport;

publicclassUploadActionextendsActionSupport{
privateFilefile;
privateStringcontentType;
privateStringfilename;

publicvoidsetUpload(Filefile){
this.file=file;
}

publicvoidsetUploadContentType(StringcontentType){
this.contentType=contentType;
}

publicvoidsetUploadFileName(Stringfilename){
this.filename=filename;
}

publicStringexecute(){
//...
returnSUCCESS;
}
}
Thepurposeofeachoneofthesemethodsisdescribedinthetablebelow.Noticethatifyouhavemultiplefile
formelementswithdifferentnamesyouwouldberequiredtohaveanothercorrespondingsetofthese
methodsforeachfileuploaded.
MethodSignature

Description

setX(Filefile)

Thefilethatcontainsthecontentoftheuploadedfile.Thisisatemporaryfile
andfile.getName()willnotreturntheoriginalnameofthefile

setXContentType(String
contentType)

Themimetypeoftheuploadedfile

setXFileName(String

Theactualfilenameoftheuploadedfile(nottheHTMLname)

https://cwiki.apache.org/confluence/display/WW/File+Upload

3/11

4/22/2015

FileUploadApacheStruts2DocumentationApacheSoftwareFoundation

fileName)

UploadingMultipleFiles
Asmentionedintheprevioussectiononetechniqueforuploadingmultiplefileswouldbetosimplyhave
multipleforminputelementsoftypefileallwithdifferentnames.Thiswouldrequireanumberofsetter
methodsthatwasequalto3timesthenumberoffilesbeinguploaded.AnotheroptionistouseArraysor
java.util.Lists.ThefollowingexamplesaretakenfromtheShowcaseexampleapplicationthatispartsample
applicationsyoucandownloadathttp://struts.apache.org/download.cgi.FortheActionmappingdetailssee
strutsfileupload.xmlinthesampleapplicationdownload.

UploadingMultipleFilesusingArrays
multipleUploadUsingArray.jspNoticeallfileinputtypeshavethesamename.
Errorformattingmacro:snippet:java.lang.IndexOutOfBoundsException:Index:20,Size:20
MultipleFileUploadUsingArrayAction.java
packageorg.apache.struts2.showcase.fileupload;

importcom.opensymphony.xwork2.ActionSupport;

importjava.io.File;

/**
*Showcaseactionmutiplefileuploadusingarray.
*
*@version$Date$$Id$
*/
publicclassMultipleFileUploadUsingArrayActionextendsActionSupport{

privateFile[]uploads;
privateString[]uploadFileNames;
privateString[]uploadContentTypes;

publicStringupload()throwsException{
System.out.println("\n\nupload2");
System.out.println("files:");
for(Fileu:uploads){
System.out.println("***"+u+"\t"+u.length());
}
System.out.println("filenames:");
for(Stringn:uploadFileNames){
https://cwiki.apache.org/confluence/display/WW/File+Upload

4/11

4/22/2015

FileUploadApacheStruts2DocumentationApacheSoftwareFoundation

System.out.println("***"+n);
}
System.out.println("contenttypes:");
for(Stringc:uploadContentTypes){
System.out.println("***"+c);
}
System.out.println("\n\n");
returnSUCCESS;
}

publicFile[]getUpload(){
returnthis.uploads;
}

publicvoidsetUpload(File[]upload){
this.uploads=upload;
}

publicString[]getUploadFileName(){
returnthis.uploadFileNames;
}

publicvoidsetUploadFileName(String[]uploadFileName){
this.uploadFileNames=uploadFileName;
}

publicString[]getUploadContentType(){
returnthis.uploadContentTypes;
}

publicvoidsetUploadContentType(String[]uploadContentType){
this.uploadContentTypes=uploadContentType;
}
}

UploadingMultipleFilesusingLists
multipleUploadUsingList.jspNoticeallfileinputtypeshavethesamename.
Errorformattingmacro:snippet:java.lang.IndexOutOfBoundsException:Index:20,Size:20
MultipleFileUploadUsingListAction.java
packageorg.apache.struts2.showcase.fileupload;

importcom.opensymphony.xwork2.ActionSupport;
https://cwiki.apache.org/confluence/display/WW/File+Upload

5/11

4/22/2015

FileUploadApacheStruts2DocumentationApacheSoftwareFoundation

importjava.io.File;
importjava.util.ArrayList;
importjava.util.List;

/**
*ShowcaseactionmultiplefileuploadusingList
*
*@version$Date$$Id$
*/
publicclassMultipleFileUploadUsingListActionextendsActionSupport{

privateList<File>uploads=newArrayList<File>();
privateList<String>uploadFileNames=newArrayList<String>();
privateList<String>uploadContentTypes=newArrayList<String>();

publicList<File>getUpload(){
returnthis.uploads;
}

publicvoidsetUpload(List<File>uploads){
this.uploads=uploads;
}

publicList<String>getUploadFileName(){
returnthis.uploadFileNames;
}

publicvoidsetUploadFileName(List<String>uploadFileNames){
this.uploadFileNames=uploadFileNames;
}

publicList<String>getUploadContentType(){
returnthis.uploadContentTypes;
}

publicvoidsetUploadContentType(List<String>contentTypes){
this.uploadContentTypes=contentTypes;
}

publicStringupload()throwsException{

System.out.println("\n\nupload1");
System.out.println("files:");
https://cwiki.apache.org/confluence/display/WW/File+Upload

6/11

4/22/2015

FileUploadApacheStruts2DocumentationApacheSoftwareFoundation

for(Fileu:uploads){
System.out.println("***"+u+"\t"+u.length());
}
System.out.println("filenames:");
for(Stringn:uploadFileNames){
System.out.println("***"+n);
}
System.out.println("contenttypes:");
for(Stringc:uploadContentTypes){
System.out.println("***"+c);
}
System.out.println("\n\n");
returnSUCCESS;
}
}

AdvancedConfiguration
TheStruts2default.propertiesfiledefinesseveralsettingsthataffectthebehavioroffileuploading.You
mayfindinnecessarytochangethesevalues.Thenamesanddefaultvaluesare:
struts.multipart.parser=jakarta
struts.multipart.saveDir=
struts.multipart.maxSize=2097152

Pleaserememberthatthestruts.multipart.maxSizeisthesizelimitofthewholerequest,which
meanswhenyouuploadingmultiplefiles,thesumoftheirsizemustbebelowthe
struts.multipart.maxSize!
Inordertochangethesessettingsyoudefineaconstantinyourapplicationsstruts.xmlfilelikeso:
<?xmlversion="1.0"encoding="UTF8"?>
<!DOCTYPEstrutsPUBLIC
"//ApacheSoftwareFoundation//DTDStrutsConfiguration2.0//EN"
"http://struts.apache.org/dtds/struts2.0.dtd">
<struts>
<constantname="struts.multipart.maxSize"value="1000000"/>
...
</struts>
AdditionallythefileUploadinterceptorhassettingsthatcanbeputinplaceforindividualactionmappingsby
customizingyourinterceptorstack.
https://cwiki.apache.org/confluence/display/WW/File+Upload

7/11

4/22/2015

FileUploadApacheStruts2DocumentationApacheSoftwareFoundation

<actionname="doUpload"class="com.example.UploadAction">
<interceptorrefname="basicStack"/>
<interceptorrefname="fileUpload">
<paramname="allowedTypes">text/plain</param>
</interceptorref>
<interceptorrefname="validation"/>
<interceptorrefname="workflow"/>

<resultname="success">good_result.jsp</result>
</action>

FileSizeLimits
Therearetwoseparatefilesizelimits.Firstisstruts.multipart.maxSizewhichcomesfromtheStruts2
default.propertiesfile.Thissettingexistsforsecurityreasonstoprohibitamalicioususerfromuploading
extremelylargefilestofileupyourserversdiskspace.Thissettingdefaultstoapproximately2megabytes
andshouldbeadjustedtothemaximumsizefile(2gigsmax)thatyourwillneedtheframeworktoreceive.If
youareuploadingmorethanonefileonaformthestruts.multipart.maxSizeappliestothecombined
total,nottheindividualfilesizes.Theothersetting,maximumSize,isaninterceptorsettingthatisusedto
ensureaparticularActiondoesnotreceiveafilethatistoolarge.Noticethelocationsofbothsettingsinthe
followingexample:
<?xmlversion="1.0"encoding="UTF8"?>
<!DOCTYPEstrutsPUBLIC
"//ApacheSoftwareFoundation//DTDStrutsConfiguration2.0//EN"
"http://struts.apache.org/dtds/struts2.0.dtd">
<struts>
<constantname="struts.multipart.maxSize"value="1000000"/>

<actionname="doUpload"class="com.example.UploadAction">
<interceptorrefname="basicStack"/>
<interceptorrefname="fileUpload">
<paramname="maximumSize">500000</param>
</interceptorref>
<interceptorrefname="validation"/>
<interceptorrefname="workflow"/>

<resultname="success">good_result.jsp</result>
</action>
</struts>

FileTypes
https://cwiki.apache.org/confluence/display/WW/File+Upload

8/11

4/22/2015

FileUploadApacheStruts2DocumentationApacheSoftwareFoundation

Therearetwowaystolimittheuploadedfiletype,declarativelyandprogrammatically.Todeclarativelylimit
thefiletypeacommaseparatedlistofallowedTypescanbespecifiedasafileUploadinterceptorparamas
showninthefollowingexample:
<actionname="doUpload"class="com.example.UploadAction">
<interceptorrefname="basicStack"/>
<interceptorrefname="fileUpload">
<paramname="allowedTypes">image/jpeg,image/gif</param>
</interceptorref>
<interceptorrefname="validation"/>
<interceptorrefname="workflow"/>

<resultname="success">good_result.jsp</result>
</action>
WhentheuploadedfiletypedoesnotmatchoneoftheMIMEtypesspecifiedafielderrorwillbecreatedas
describedinthenextsectionentitledErrorMessages.Programmaticallylimitingthefiletypemeansusingthe
informationpassedintoyourActionclassviathesetXContentType(StringcontentType)method.The
benefittothistypeofapproachwouldbethatit'smoreflexibleandnointerceptorconfigurationwouldbe
needediffilesizesarekeepunder2megs.

ErrorMessages
Ifanerroroccursseveralfielderrorswillbeaddedassumingthattheactionimplements
com.opensymphony.xwork2.ValidationAwareorextendscom.opensymphony.xwork2.ActionSupport.
Theseerrormessagesarebasedonseverali18nvaluesstoredinstrutsmessages.properties,adefaulti18n
fileprocessedforalli18nrequests.Youcanoverridethetextofthesemessagesbyprovidingtextforthe
followingkeys:
ErrorKey

Description

struts.messages.error.uploading

Ageneralerrorthatoccurswhenthefile
couldnotbeuploaded

struts.messages.error.file.too.large

Occurswhentheuploadedfileistoolarge
asspecifiedbymaximumSize.

struts.messages.error.content.type.not.allowed

Occurswhentheuploadedfiledoesnot
matchtheexpectedcontenttypesspecified

struts.messages.error.file.extension.not.allowed

Occurswhenuploadedfilehasdisallowed
extension

struts.messages.upload.error.SizeLimitExceededException

Occurswhentheuploadrequest(asa
whole)exceedconfigured
struts.multipart.maxSize

https://cwiki.apache.org/confluence/display/WW/File+Upload

9/11

4/22/2015

FileUploadApacheStruts2DocumentationApacheSoftwareFoundation

struts.messages.upload.error.<Exceptionclass
SimpleName>

Occurswhenanyotherexceptiontook
placeduringfileuploadprocess

TemporaryDirectories
AlluploadedfilesaresavedtoatemporarydirectorybytheframeworkbeforebeingpassedintoanAction.
Dependingontheallowedfilesizesitmaybenecessarytohavetheframeworkstorethesetemporaryfilesin
analternatelocation.Todothischangestruts.multipart.saveDirtothedirectorywheretheuploaded
fileswillbeplaced.Ifthispropertyisnotsetitdefaultstojavax.servlet.context.tempdir.Keepinmind
thatonsomeoperatingsystems,likeSolaris,/tmpismemorybasedandfilesstoredinthatdirectorywould
consumeanamountofRAMapproximatelyequaltothesizeoftheuploadedfile.

AlternateLibraries
Thestruts.multipart.parserusedbythefileUploadinterceptortohandleHTTPPOSTrequests,encoded
usingtheMIMEtypemultipart/formdata,canbechangedout.Currentlytherearetwochoices,jakartaand
pell.ThejakartaparserisastandardpartoftheStruts2frameworkneedingonlyitsrequiredlibrariesadded
toaproject.ThepellparserusesJasonPell'smultipartparserinsteadoftheCommonsFileUploadlibrary.
ThepellparserisaStruts2plugin,formoredetailssee:http://cwiki.apache.org/S2PLUGINS/pellmultipart
plugin.html.Therewasathirdalternative,cos,butitwasremovedduetolicensingincompatibilities.
AsfromStrutsversion2.3.18anewimplementationofMultiPartRequestwasadded
JakartaStreamMultiPartRequest.Itcanbeusedtohandlelargefiles,seeWW3025formoredetails,but
youcansimpleset
<constantname="struts.multipart.parser"value="jakartastream"/>
instruts.xmltostartusingit.
Nolabels

2Comments
CedricLevasseur
pleasereplace"publicUploadActionextendsActionSupport{"by
"publicclassUploadActionextendsActionSupport{"
PhilipLuppens
Fixedthanksforreporting!

PoweredbyafreeAtlassianConfluenceOpenSourceProjectLicense
grantedtoApacheSoftwareFoundation.EvaluateConfluencetoday.
ThisConfluenceinstallationrunsaFreeGliffyLicenseEvaluatetheGliffy
ConfluencePluginforyourWiki!
https://cwiki.apache.org/confluence/display/WW/File+Upload

10/11

4/22/2015

FileUploadApacheStruts2DocumentationApacheSoftwareFoundation

https://cwiki.apache.org/confluence/display/WW/File+Upload

11/11

Вам также может понравиться