Apache Commons FileUpload File upload instance explanation _java

Source: Internet
Author: User
Tags save file

File upload methods are currently two commonly used, one is smartupload, one is Apache Commons fileupload.

We are here to introduce the second use of the first to upload files, pay attention to a few questions:

1 Form form, to add space <input type= "file" name= "MyFile" >

2 Form form content format to be defined as Multipart/form-data format

3 needs class Library: 1 Commons-io.jar 2commons-fileupload-1.3.1.jar

Next we look at the usage.

The first reading of the official documents of the Apache Commons FileUpload can be found in the following several commonly used functions:

1 Creating File Resolution objects

Copy Code code as follows:
Diskfileupload diskfileupload = new Diskfileupload ();

2 file parsing is placed in the list, because this class library supports multiple file uploads, so the results will exist in the list.

Copy Code code as follows:
list<fileitem> list = diskfileupload.parserequest (request);

3 Get upload file for analysis (not required)

Copy Code code as follows:
File RemoteFile = new file (new String (Fileitem.getname (). GetBytes (), "UTF-8"));

4 Create a new object and stream a copy

File1 = new File (This.getservletcontext (). Getrealpath ("attachment"), Remotefile.getname ());
            File1.getparentfile (). Mkdirs ();
            File1.createnewfile ();
            
            InputStream ins = Fileitem.getinputstream ();
            OutputStream ous = new FileOutputStream (file1);
            
            try{
              byte[] buffer = new byte[1024];
              int len = 0;
              while (len = ins.read (buffer)) >-1)
                ous.write (Buffer,0,len);
              Out.println ("Save File" +file1.getabsolutepath () + "<br/>");
            } finally{
              ous.close ();
              Ins.close ();
            }

This completes the upload of the file.

Fileupload.html

 <form action= "Servlet/uploadservlet" method= "post" enctype= "Multipart/form-data" > <div align= "Center" > <fieldset style= "width:80%" > <legend> upload file </legend><br/> <div align= "left "> Upload file 1</div> <div align=" left "> <input type=" file "name=" File1 "/> &L T;/div> <div align= "left" > upload file 2</div> <div align= "left" > <input ty Pe= "File" name= "File2"/> </div> <div> <div align= ' left ' > upload file Description 1</d iv> <div align= ' left ' ><input type= ' text ' name= ' description1 '/></div> &LT;/DIV&G
          T <div> <div align= ' left ' > upload file description 2</div> <div align= ' left ' ><input type= ' te 
          XT "Name=" Description2 "/></div> </div> <div> <div align= ' left ' >    <input type= ' Submit ' value= "Upload file"/> </div> </div> </fieldset>

 </div> </form>

Xml

<servlet>
  <servlet-name>UploadServlet</servlet-name>
  <servlet-class> com.test.hello.uploadservlet</servlet-class>
 </servlet>
<servlet-mapping>
  < Servlet-name>uploadservlet</servlet-name>
  <url-pattern>/servlet/uploadservlet</ Url-pattern>
 </servlet-mapping>

Uploadservlet.java

Package Com.test.hello;
Import Java.io.File;
Import Java.io.FileOutputStream;
Import java.io.IOException;
Import Java.io.InputStream;
Import Java.io.OutputStream;
Import Java.io.PrintWriter;

Import java.util.List;
Import javax.servlet.ServletException;
Import Javax.servlet.http.HttpServlet;
Import Javax.servlet.http.HttpServletRequest;

Import Javax.servlet.http.HttpServletResponse;
Import Org.apache.commons.fileupload.DiskFileUpload;
Import Org.apache.commons.fileupload.FileItem;

Import org.apache.commons.fileupload.FileUploadException;
   The public class Uploadservlet extends HttpServlet {/** * constructor of the object.
  * * Public Uploadservlet () {super (); }/** * Destruction of the servlet. <br>/public void Destroy () {Super.destroy ();//Just puts ' destroy ' string in Log//Put your code here}/** * The Doget method of the servlet.
   <br> * This is called when a form has it tag value method equals to get.* @param request the request send by the "client to the" server * @param response the response send by the server T o the client * @throws servletexception If an error occurred * @throws IOException If a error occurred * * Publ

    IC void doget (HttpServletRequest request, httpservletresponse response) throws Servletexception, IOException {
    Response.setcharacterencoding ("UTF-8");
  Response.getwriter () println ("Please upload the file as post"); /** * The DoPost method of the servlet.
   <br> * * This are called when a form has it tag value method equals to post. * @param request the request send by the "client to the" server * @param response the response send by the server T o the client * @throws servletexception If an error occurred * @throws IOException If a error occurred * * * @Sup Presswarnings ({"Unchecked", "deprecation"}) public void DoPost (HttpServletRequest request, HttpServletResponse Respon SE) throws ServletexceptIon, IOException {File file1 = null,file2=null;
    String Description1 = Null,description2 = null;
    Response.setcharacterencoding ("UTF-8");
    Request.setcharacterencoding ("UTF-8");
    Response.setcontenttype ("text/html");
    
    PrintWriter out = Response.getwriter ();
    Diskfileupload diskfileupload = new Diskfileupload ();
      
      try{list<fileitem> List = diskfileupload.parserequest (request);
      Out.println ("Traverse all fileitem...<br/>"); for (Fileitem fileitem:list) {if (Fileitem.isformfield ()) {if ("Description1". Equals (Fileitem.getfieldnam
            E ()) {out.println ("Traversal to Description1 ... <br/>");
          Description1 = new String (fileitem.getstring (). GetBytes (), "UTF-8"); } if ("Description2". Equals (Fileitem.getfieldname ()) {out.println ("traverse to Description2 ... <br/>")
            ;
          Description2 = new String (fileitem.getstring (). GetBytes (), "UTF-8");
     }}else{     if ("File1". Equals (Fileitem.getfieldname ())) {File RemoteFile = new File (New String (Fileitem.getname (). Get
            Bytes (), "UTF-8"));
            Out.println ("Traverse to file1...<br/>");
            
            OUT.PRINTLN ("Client file location:" +remotefile.getabsolutepath () + "<br/>");
            File1 = new File (This.getservletcontext (). Getrealpath ("attachment"), Remotefile.getname ());
            File1.getparentfile (). Mkdirs ();
            
            File1.createnewfile ();
            InputStream ins = Fileitem.getinputstream ();
            
            OutputStream ous = new FileOutputStream (file1);
              try{byte[] buffer = new byte[1024];
              int len = 0;
              while (len = ins.read (buffer)) >-1) ous.write (Buffer,0,len);
            Out.println ("To save the file" +file1.getabsolutepath () + "<br/>");
              }finally{Ous.close ();
            Ins.close (); } if ("File2". Equals (f)Ileitem.getfieldname ()) {File RemoteFile = new file (new String (Fileitem.getname (). GetBytes (), "UTF-8"));
            Out.println ("Traverse to file2...<br/>");
            
            OUT.PRINTLN ("Client file location:" +remotefile.getabsolutepath () + "<br/>");
            File2 = new File (This.getservletcontext (). Getrealpath ("attachment"), Remotefile.getname ());
            File2.getparentfile (). Mkdirs ();
            
            File2.createnewfile ();
            InputStream ins = Fileitem.getinputstream ();
            
            OutputStream ous = new FileOutputStream (file2);
              try{byte[] buffer = new byte[1024];
              int len = 0;
              while (len = ins.read (buffer)) >-1) ous.write (Buffer,0,len);
            Out.println ("To save the file" +file2.getabsolutepath () + "<br/>");
              }finally{Ous.close ();
            Ins.close (); }} out.println ("Request resolution completed &LT;BR/&GT;<br/> "); }}catch (Fileuploadexception e) {} out.println ("<!
    DOCTYPE HTML public \-//w3c//dtd HTML 4.01 transitional//en\ ">");
    Out.println ("<HTML>");
    Out.println (" 

Running the sample

The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.

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.