Apache Commons fileupload File Upload multiple sample sharing _java

Source: Internet
Author: User
Tags static class

This article introduces how to use the Commons-fileupload.jar,apache Commons-fileupload.jar to realize the uploading function of the file by the example, the concrete contents are as follows

The Apache Commons-fileupload.jar is placed under the web-inf\lib of the application and can be used. The following example describes how to use its file upload feature.

The FileUpload version used is 1.2 and the environment is eclipse3.3+myeclipse6.0. FileUpload is based on Commons io, so make sure that the Commons IO jar package (used Commons-io-1.3.2.jar) is under Web-inf\lib before entering the project.
This article is an example project that can be downloaded in the final attachment of the article.

Example 1

In the simplest case, by servletfileupload the static class to parse the request, the factory class Fileitemfactory will handle all the fields in the Mulipart class's form, not just the file field. GetName () Gets the file name, getString () Gets the form data content, Isformfield () can determine whether it is a normal form item.
Demo1.html

 
 

demo1.jsp

<%@ page language= "java" contenttype= "text/html; charset=gb18030 "pageencoding=" GB18030 "%> <%@ page import=" org.apache.commons.fileupload.* "%> <%@ page Import= "org.apache.commons.fileupload.servlet.*"%> <%@ page import= "org.apache.commons.fileupload.disk.*"% > <%@ page import= "java.util.*"%> <! DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en" > <% boolean ismultipart = Servletfileupload.ismultipa
  Rtcontent (Request)//Check whether the input requests are multipart form data. if (Ismultipart = = True) {Fileitemfactory factory = new Diskfileitemfactory ()//Create a Diskfileitemfactory object for the request to parse Please.
    After parsing is performed, all form items are saved in a list.
    Servletfileupload upload = new Servletfileupload (factory);
    list<fileitem> items = upload.parserequest (request);
    iterator<fileitem> ITR = Items.iterator ();
      while (Itr.hasnext ()) {Fileitem item = (Fileitem) itr.next ();
      Check whether the current item is a normal form item or an upload file.
    if (Item.isformfield ()) {//If it is a plain form item, display the contents of the form. String FIELDName = Item.getfieldname (); if (fieldname.equals ("name"))//corresponds to demo1.html type= "text" name= "name" Out.print ("the field name is" + item.getstring (
    );//Displays the contents of the form.
      Out.print ("<br>");
    else {//If the file is uploaded, display the filename.
    Out.print ("The Upload file name is" + item.getname ());
      Out.print ("<br>");
  }} else {Out.print ("The enctype must be Multipart/form-data"); }%>  

Results:
The field name Isjeff
The upload file name isd:\c language Exam sample/job title. rar

Example 2

Upload two files to the specified directory.

Demo2.html

 
 

demo2.jsp

<%@ page language= "java" contenttype= "text/html; charset=gb18030 "pageencoding=" GB18030 "%> <%@ page import=" org.apache.commons.fileupload.* "%> <%@ page Import= "org.apache.commons.fileupload.servlet.*"%> <%@ page import= "org.apache.commons.fileupload.disk.*"% > <%@ page import= "java.util.*"%> <%@ page import= "java.io.*"%> <!
 DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en" > <%string uploadpath= "d:\\temp";
 Boolean ismultipart = servletfileupload.ismultipartcontent (request);
    if (ismultipart==true) {try{Fileitemfactory factory = new Diskfileitemfactory ();
    Servletfileupload upload = new Servletfileupload (factory);
    list<fileitem> items = upload.parserequest (request);//Get all files iterator<fileitem> ITR = Items.iterator ();
     while (Itr.hasnext ()) {//process each file sequentially Fileitem item= (Fileitem) itr.next (); String filename=item.getname ();//Get file name, including path if (filename!=null) {file Fullfile=new file (item. GetName ());
       File Savedfile=new file (Uploadpath,fullfile.getname ());
     Item.write (Savedfile);
   } out.print ("Upload succeed");
   catch (Exception e) {e.printstacktrace ();
 } else{out.println ("The enctype must be Multipart/form-data"); }%>  

Results:
Upload Succeed

At this point, under "D:\temp" you can see the two files you uploaded.

Example 3

Upload a file to the specified directory and qualify the file size.

Demo3.html

 
 

demo3.jsp

<%@ page language= "java" contenttype= "text/html; charset=gb18030 "pageencoding=" GB18030 "%> <%@ page import=" org.apache.commons.fileupload.* "%> <%@ page Import= "org.apache.commons.fileupload.servlet.*"%> <%@ page import= "org.apache.commons.fileupload.disk.*"% > <%@ page import= "java.util.*"%> <%@ page import= "java.io.*"%> <!
  DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en" > <% file Uploadpath = new file ("D:\\temp");//Upload Directory
  if (!uploadpath.exists ()) {uploadpath.mkdirs ();
  }//Temporary files directory file Temppathfile = new file ("d:\\temp\\buffer\\");
  if (!temppathfile.exists ()) {temppathfile.mkdirs ();
 
    try {//Create a factory for disk-based file items Diskfileitemfactory factory = new Diskfileitemfactory (); Set Factory Constraints Factory.setsizethreshold (4096); Set buffer size, here is 4KB factory.setrepository (temppathfile);//Set buffer directory//Create a new file upload handler servletf Ileupload UPLOad = new Servletfileupload (factory); Set Overall request size constraint Upload.setsizemax (4194304); Set maximum file size, here is 4MB list<fileitem> items = upload.parserequest (request);/Get all the files iterator<fileitem>
    i = Items.iterator ();
      while (I.hasnext ()) {Fileitem fi = (Fileitem) i.next ();
      String fileName = Fi.getname ();
    if (fileName!= null) {File FullFile = new file (Fi.getname ());
    File Savedfile = new file (Uploadpath, fullfile. GetName ());
      Fi.write (Savedfile);
  } out.print ("Upload succeed");
  catch (Exception e) {e.printstacktrace (); }%>  

Example 4

Use servlet to implement file uploads.

Upload.java

Package com.zj.sample;
Import Java.io.File;
Import java.io.IOException;
Import Java.util.Iterator;
 
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.FileItem;
Import Org.apache.commons.fileupload.disk.DiskFileItemFactory;
 
Import Org.apache.commons.fileupload.servlet.ServletFileUpload; 
  @SuppressWarnings ("Serial") public class Upload extends HttpServlet {private String Uploadpath = "d:\\temp";//directory of uploaded files Private String TempPath = "d:\\temp\\buffer\\";
 
  Temporary files directory file temppathfile;  @SuppressWarnings ("unchecked") public void DoPost (HttpServletRequest request, httpservletresponse response) throws IOException, Servletexception {try {//Create a factory for disk-based file items diskfileitemfactory F
 
      Actory = new Diskfileitemfactory ();
 Set Factory constraints     Factory.setsizethreshold (4096); Set buffer size, here is 4KB factory.setrepository (temppathfile);//Set buffer directory//Create a new file upload handler S
 
      Ervletfileupload upload = new Servletfileupload (factory); Set Overall request size constraint Upload.setsizemax (4194304); Set maximum file size, here is 4MB list<fileitem> items = upload.parserequest (request);/Get all the files Iterator<fileitem
      > i = Items.iterator ();
       while (I.hasnext ()) {Fileitem fi = (Fileitem) i.next ();
       String fileName = Fi.getname ();
         if (fileName!= null) {File FullFile = new file (Fi.getname ());
         File Savedfile = new file (Uploadpath, Fullfile.getname ());
       Fi.write (Savedfile);
    } System.out.print ("Upload succeed");
    catch (Exception e) {//Can jump error page e.printstacktrace ();
    } public void Init () throws servletexception {file UploadFile = new File (Uploadpath); if (!uploadfile.exists ()) {
      Uploadfile.mkdirs ();
    } File Temppathfile = new file (TempPath);
    if (!temppathfile.exists ()) {temppathfile.mkdirs ();
 }
  }
}

Demo4.html

 
 

Xml

<servlet>
  <servlet-name>Upload</servlet-name>
  <servlet-class> com.zj.sample.upload</servlet-class>
</servlet>
 
<servlet-mapping>
  < servlet-name>upload</servlet-name>
  <url-pattern>/fileupload</url-pattern>
</ Servlet-mapping>

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.