- First step: Load Commons-fileupload-1.2.1.jar, Commons-1.3.2.jar under Web-inf/lib. These two files are available for download from http://commons.apache.org/.
- The second step: set the From table Enctype to: "Multipart/form-data", as follows:
<enctype= "Multipart/form-data" action= "${ Pagecontext.request.contextpath}/list.action " method=" POST " <input type = "File" name = "Uploadimage" > </ form >
- Step Three: Add the following code to the action class:
Packagecn.itcast.action;ImportJava.io.File;Importorg.apache.commons.io.FileUtils;ImportOrg.apache.struts2.ServletActionContext;ImportCom.opensymphony.xwork2.ActionContext; Public classhelloworldaction {PrivateFile image; PrivateString Imagefilename; PublicString Getimagefilename () {returnImagefilename; } Public voidsetimagefilename (String imagefilename) { This. Imagefilename =Imagefilename; } PublicFile getImage () {returnimage; } Public voidsetimage (File image) { This. Image =image; } PublicString Addui () {return"Success"; } PublicString Execute ()throwsexception{String Realpath= Servletactioncontext.getservletcontext (). Getrealpath ("/images");//the directory where the files are saved (the absolute path to the file)System.out.println (Realpath); if(image!=NULL) {File savefile=NewFile (NewFile (Realpath), imagefilename);//SaveFile is a full file path if(!savefile.getparentfile (). exists ()) Savefile.getparentfile (). Mkdirs ();//Create a directory if the directory where the file is saved does not existFileutils.copyfile (image, SaveFile);//Call system function Copy file image to SaveFileActioncontext.getcontext (). Put ("message", "Upload succeeded"); } return"Success"; }}
The 4.struts.xml file configuration is as follows:
<Struts> <constantname= "Struts.enable.DynamicMethodInvocation"value= "false"/> <!--control the size of file uploads - <constantname= "Struts.multipart.maxSize"value= "10701096"/> < Packagename= "Employee"extends= "Struts-default"> <Actionname= "List_*"class= "Cn.itcast.action.HelloWorldAction"Method= "{1}"> <resultname= "Success">/web-inf/page/message.jsp</result> </Action> </ Package></Struts>
Strut2 Single File Upload