Struts2 Single File upload/multiple file upload

Source: Internet
Author: User

1 importing Struts2-blank.war all jar packages: \struts-2.3.4\apps\struts2-blank.war

Single File Upload

upload.jsp

<s:form action= "Upload2.action" method= "POST" theme= "simple" enctype= "Multipart/form-data" ><tr>       <TD id= "More" >              Select Upload file:<s:file name= "file" ></s:file><br>             <s:submit Type= "button" value= "Submit"/>         </td>  </tr></s:form>

Struts.xml

<Packageextends= "Struts-default" >    <action name= "upload2"class= " Com.hloytax.wg.upload?. UploadAction1 ">           <result name=" Success ">/success.jsp</result>            <interceptor-ref name=" FileUpload ">                 <param name=" MaximumSize ">409600</param>//Upload file Size settings                //<!--allowedtypes (optional )-comma-separated list of contentType types (e.g. text/html), <param name= "ContentType" > Application/txt; </param>
<param name= "Allowedtypes" > </param> </interceptor-ref> <interceptor-ref Name = "Defaultstack" ></interceptor-ref> </action> </Package >
Uploadaction1.action
 Public classUploadAction1extendsActionsupport {/**     *      */    Private Static Final LongSerialversionuid = 1L; Privatefile file; //file name    PrivateString Filefilename; //File Type    PrivateString Filecontenttype; //Note: The name prefix of the file name and file type must be the same,    omit Get Set method@Override PublicString Execute ()throwsexception{//get the file path of the file you want to uploadFile uploadfile=NewFile (Servletactioncontext.getservletcontext (). Getrealpath ("UploadFile")); //determine if the file is uploaded, and if it is uploaded, the directory will be created.        if(!uploadfile.exists ()) {Uploadfile.mkdir ();//Create the directory        }                    /*//First File Upload method//Declare file input stream, specify file path for input stream FileInputStream input=new fileinputstream (file);                    Gets the output stream, gets the file address and name of the file FileOutputStream out=new fileoutputstream (uploadfile + "\ \" +filefilename);              try{byte[] B=new byte[1024];//the size of each write int i=0;              while ((I=input.read (b)) >0) {out.write (b,0,i);          }}catch (Exception e) {e.printstacktrace ();              }finally{Input.close ();          Out.close (); }            */                            //the second method of uploading files//fileutils.copyfile (file,new file (uploadfile+ "\ \" +filefilename)); //fileutils.copyfile (file,new file (uploadfile,filefilename)); //System.out.println (UploadFile); //The third method ofBufferedReader breader=NewBufferedReader (NewInputStreamReader (Newfileinputstream (file)); BufferedWriter Bwriter=NewBufferedWriter (NewOutputStreamWriter (NewFileOutputStream (uploadfile+ "\ \" +( filefilename)));         System.out.println (UploadFile); Try{            Char[] str=New Char[1024]; intI=0;  while((I=breader.read (str)) >0) {bwriter.write (str,0, i); }        }Catch(Exception e) {e.printstacktrace (); }finally{breader.close ();            Bwriter.close ();        Uploadfile.delete (); }                    returnSUCCESS; }    

Xml

<?xml version= "1.0" encoding= "UTF-8"? ><web-app xmlns:xsi= "Http://www.w3.org/2001/XMLSchema-instance"     xmlns= "Http://java.sun.com/xml/ns/javaee"    xsi:schemalocation= "http://java.sun.com/xml/ Ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd "    id=" webapp_id "version=" 2.5 ">    <filter>        <filter-name>struts2</filter-name>        <filter-class> org.apache.struts2.dispatcher.ng.filter.strutsprepareandexecutefilter</filter-class>    </filter>    <filter-mapping>        <filter-name>struts2</filter-name>        < url-pattern>/*</url-pattern>    </filter-mapping></web-app>
Multiple file uploads:
PrivateList<file>file;PrivateList<string>Filecontenttype;PrivateList<string>Filefilename;
private String Savepath;Omit get Set method upload method reference single File upload
@Override
Public String Execute () throws Exception {
List<file> files= getFile ();
if (Files!=null) {
for (int i = 0; i < files.size (); i++) {
FileOutputStream fos = new FileOutputStream (Getsavepath () + "\ \" + getfilefilename (). get (i));
Create an input stream to upload files
System.out.println (Getsavepath ());
FileInputStream fis = new FileInputStream (Files.get (i));

byte[] buffer = new byte[1024];
int len = 0;
while (len = fis.read (buffer)) > 0) {
Fos.write (buffer, 0, Len);
}
Fis.close ();
Fos.close ();
}
}
return SUCCESS;

}

/**
* Returns the location where the uploaded file was saved
*
* @return
* @throws Exception
*/
Public String Getsavepath () throws Exception {
Return Servletactioncontext.getservletcontext (). Getrealpath (Savepath);
}
public void Setsavepath (String savepath) {
This.savepath = Savepath;
}

Struts2 Single File upload/multiple 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.