/* Prerequisites for File Upload * 1. The uploaded form must be submitted by post (method= "post") * 2. The submission requires the specified encoding: ' multipart/form-data ' (enctype= "multipart/form-data ' ") * 3. You can add a result of name= "input" to the XML configuration file to make it easier to echo the error message * 4. If the downloaded file is too large, you need to modify the default file maximum number of bytes in the XML configuration file, such as maximum allowable upload of 5 m: * "* <constant name=" struts.multipart.maxSize "value=" 5242880 "/> * * * *
1. Upload the code in the JSP page:
Introducing S-tags
<!--from form - <S:fielderrorFieldName= "file"></S:fielderror> Error message Tips <S:formAction= "/fileupload"Method= "post"Theme= "simple"enctype= "multipart/form-data"> <!--Select File Tab - <S:filename= "file" /> <!--Submit Button - <S:submitvalue= "upload" /> </S:form>
2. Actions for the specific action class:
public classFileuploadactionextendsActionsupport {Private Static Final LongSerialversionuid = 1L; //file and JSP page [<s:fielderror fieldname= "file" ></s:fielderror>]fieldname . Privatefile file; //file name passed in: PrivateString filefilename; //file types passed in: PrivateString filecontenttype;
Getter,setter method for generating three fields
//Business Processing publicString Execute ()throwsException {//gets the path to "/123"String Path = Servletactioncontext.getservletcontext (). Getrealpath ("/123"); //take the file type "/" intercept, get the last element [1], string concatenation//filename=uuid. File TypeString filename=uuid.randomuuid (). toString () + "." +filecontenttype.split ("/") [1]; //build a file named filename in "/123"File files=NewFile (path,filename); //copy files from file to file named filename in '/123 'fileutils.copyfile (file, files); returnNONE; }
Code in 3.struts.xml:
<Struts> <!--Maximum upload byte size allowed by server - <constantname= "struts.multipart.maxSize"value= "5242880"></constant> <includefile= "struts-default.xml"></include> < packagename= "fileuploads"extends= "struts-default"> <Actionname= "fileupload"class= "com.gxxy.filetransport.filedownload.FileUpLoadAction"> <Interceptor-refname= "fileUpload"> <!--set the byte size of the uploaded file, which can only be smaller than the maximum upload byte size allowed by the server - <paramname= "maximumsize">1048576</param> <!--set up extensions to allow uploads - <paramname= "allowedextensions">Png,jpg,txt</param> </Interceptor-ref> <Interceptor-refname= "defaultstack"/> <resultname= "input">/jsp/filetransport/fileupload.jsp</result> <resultname= "none">/jsp/filetransport/fileupload.jsp</result> </Action> </ package></Struts>
Struts File Upload