Using Apache Commons-fileupload and Ajax to implement file upload progress bar __ajax

Source: Internet
Author: User
Tags file upload progress bar

realize the idea:

1, first of all, customize a progress to implement the class Progresslistener interface, rewrite the upload method.

2, by the number of bytes read and the total number of bytes to generate a percentage, the value into the session

3. Create a servlet to get the percentage of the session

4, in the upload file interface, in the form submission, Ajax every 100 milliseconds to access the percentage value of the servlet response created in the third step, displayed in the interface.

Reference Code:

Custom Listener class Implementation Progresslistener

Package Cn.progressbar;

Import Java.text.NumberFormat;
Import Javax.servlet.http.HttpServletRequest;

Import javax.servlet.http.HttpSession;

Import Org.apache.commons.fileupload.ProgressListener; /** * Custom Listener class implementation Progresslistener * @author L *///@WebListener public class Myprogresslistener implements Progresslist
	ener{private Double megabytes =-1;
	
	Private HttpSession session; Public Myprogresslistener () {} public Myprogresslistener (HttpServletRequest request) {session = Request.getsessio
	N (); @Override public void Update (long pbytesread, long pcontentlength, int pitems) {//TODO auto-generated method Stu  b Double mBytes = pbytesread/(1024*1024);  Pbytesread a double total=pcontentlength/(1024*1024) of the number of files read so far;  
           Pcontentlength file Total size if (megabytes = = MBytes) {return;  
           } System.out.println ("Total File Size:" +total+ "M");  
           System.out.println ("read:" +mbytes+ "M"); megabytes = MbyTEs  System.out.println ("Currently reading the first few files" + Pitems);  Pitems is currently reading the first few files if (pcontentlength = = 1) {System.out.println ("so far," + Pbytesread + " Bytes have been read. ");}  
                                  else {System.out.println ("so far," + Pbytesread + "of" + pcontentlength  
              + "bytes have been read.");  
              Double read= (mbytes/total);  
              NumberFormat nf=numberformat.getpercentinstance (); System.out.println ("read===>" +nf.format (read))//Generate a percentage of the read and put in session session.setattribute ("read", NF.F  
           Ormat (read));
 }  
	}

}
Encapsulation FileUpload used to receive form fields and file fields in request
Package Cn.progressbar;
Import Java.util.HashMap;
Import Java.util.Iterator;
Import java.util.List;

Import Java.util.Map;

Import Javax.servlet.http.HttpServletRequest;
Import Org.apache.commons.fileupload.FileItem;
Import Org.apache.commons.fileupload.FileItemFactory;
Import org.apache.commons.fileupload.FileUploadException;
Import Org.apache.commons.fileupload.disk.DiskFileItemFactory;

Import Org.apache.commons.fileupload.servlet.ServletFileUpload;  
    public class FileUpload {private map<string,string> params;  
      
    private map<string,fileitem> files;  
        Public FileUpload () {params=new hashmap<string, string> ();  
    Files=new hashmap<string, fileitem> (); @SuppressWarnings ("rawtypes") public void Setmap (HttpServletRequest request) {//Create a factory F  
        or disk-based file items fileitemfactory factory = new Diskfileitemfactory (); Create a new file upload handler SERVLEtfileupload upload = new Servletfileupload (factory);  
        Upload.setheaderencoding ("Utf-8");  
            Upload.setprogresslistener (new Myprogresslistener request);/Set Progress listener//Parse the request try {  
            List items = upload.parserequest (request);  
            Iterator iter = Items.iterator ();  
                while (Iter.hasnext ()) {Fileitem item = (Fileitem) iter.next ();  
                    if (Item.isformfield ()) {String name = Item.getfieldname ();  
                    String value = item.getstring ();  
                Params.put (name, value);  
                    } else{String name=item.getfieldname ();  
                Files.put (name, item);  
        A catch (Fileuploadexception e) {e.printstacktrace ());  
    } public map<string, String> Getparams () {return params; } 
  
    Public map<string, Fileitem> GetFiles () {return files;  
        ///To get the name of the file public String GetFileName (Fileitem Item) {string Fname=item.getname ();  
        System.out.println ("fname=====>" +fname);  
        int Lastindex=fname.lastindexof ("\");  
        Fname=fname.substring (lastindex+1);  
        System.out.println ("New fname=====>" +fname);  
    return fName;  
 }  
}
Implement upload file Servlet

Package Cn.progressbar;
Import Java.io.File;
Import java.io.IOException;
Import Java.io.PrintWriter;

Import Java.util.Map;
Import javax.servlet.ServletException;
Import Javax.servlet.annotation.WebServlet;
Import Javax.servlet.http.HttpServlet;
Import Javax.servlet.http.HttpServletRequest;

Import Javax.servlet.http.HttpServletResponse;

Import Org.apache.commons.fileupload.FileItem; @WebServlet ("/fileuploadservlet") public class Fileuploadservlet extends HttpServlet {protected void doget (HttpS Ervletrequest request, HttpServletResponse response) throws Servletexception, IOException {doPost (Request, RESPO
	NSE); 
		} protected void DoPost (HttpServletRequest request, httpservletresponse response) throws Servletexception, IOException {  
        Response.setcontenttype ("Text/html;charset=utf-8");  
        PrintWriter out = Response.getwriter ();  
        FileUpload fu=new fileupload (); Fu.setmap (Request)//parsing request map<string,fileitem> FILES=FU.GETFIles ();  
        String fileName =fu.getfilename (files.get ("file"));  
        File File=new file (This.getservletcontext (). Getrealpath ("upload\\" +filename));  
              
        try {files.get ("file"). write (file);  
        catch (Exception e) {e.printstacktrace (); } out.println (' <script>alert (' upload succeeded.
	'); History.go ( -1);</script> ");
 }

}
Implement a servlet fileuploadstatus that responds to upload progress

Package Cn.progressbar;
Import java.io.IOException;

Import Java.io.PrintWriter;
Import javax.servlet.ServletException;
Import Javax.servlet.annotation.WebServlet;
Import Javax.servlet.http.HttpServlet;
Import Javax.servlet.http.HttpServletRequest;
Import Javax.servlet.http.HttpServletResponse;

Import javax.servlet.http.HttpSession; @WebServlet ("/fileuploadstatus") public class Fileuploadstatus extends HttpServlet {protected void doget ( HttpServletRequest request, HttpServletResponse response) throws Servletexception, IOException {doPost (Request, RESP
	Onse); 
		} protected void DoPost (HttpServletRequest request, httpservletresponse response) throws Servletexception, IOException { System.out.println ("-------------------------------------------------------------------------------------------
		-------------------------------");  
        Response.setcontenttype ("Text/html;charset=utf-8");  
        PrintWriter out = Response.getwriter (); HttpSession session=request.getsession ();  
          
        String status= (String) session.getattribute ("read");//Get Upload progress percent System.out.println (status+  
        "Fileuploadstatus");
 OUT.PRINTLN (status);//Response}}
index.jsp Complete Content

<%@ page language= "java" contenttype= "text/html; Charset=utf-8 "pageencoding=" UTF-8 "%> <!
DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en" "Http://www.w3.org/TR/html4/loose.dtd" >  

Effect Chart:

Note: Don't forget to quote jquery


Reference: http://blog.csdn.net/hxlzpnyist/article/details/7601611


Related Article

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.