Using Jsp+extjs to realize dynamic display file upload Progress _jsp programming

Source: Internet
Author: User
Tags file upload

The source of the demand is this: Upload a large Excel file to the server, the server will parse this Excel, and then a piece of the insert into the database, the whole process will take a long time, so when users click Upload, you need to display a progress bar, And can update the progress bar according to the amount of data received and the progress of processing in the background.

Analysis: background requires two components, uploadcontroller.jsp to receive and process the data, it will dynamically put the progress information to the session, another component processcontroller.jsp to update the progress bar, when the user point After "Upload", Form is presented to uploadcontroller.jsp, while using JS to start an AJAX request to Processcontroller.jsp,ajax update the progress bar's display progress with the percentage of progress achieved, and repeat the process every second; This is the basic principle of this example.

The question now is how does the server know how much data is received when it receives data? If we write a file upload component from scratch, the problem is very well solved, the key is that many times we are using the mature components, such as Apache Commons FileUpload; more fortunate, Apache had already thought of this problem, So the interface can be used to get the percentage of the received data, so I use the Apache Commons fileupload to receive the uploaded file.

UPLOADCONTROLLER.JSP:

<%@ page language= "java" import= "java.util.*, java.io.*, org.apache.commons.fileupload.*, Org.apache.commons.fileupload.disk.DiskFileItemFactory, Org.apache.commons.fileupload.servlet.ServletFileUpload "Pageencoding=" Utf-8 "%> <%//Note that the import jar package above is required//below is the use of Apache Commons fileupload to receive uploaded files; fileitemfactory
Factory = new Diskfileitemfactory ();
Servletfileupload upload = new Servletfileupload (factory);
Because the inner class cannot reference the request, you implement one.
	Class Myprogresslistener implements progresslistener{private httpservletrequest request = null;
	Myprogresslistener (HttpServletRequest request) {this.request = Request; public void update (long pbytesread, long pcontentlength, int pitems) {Double percentage = (double) pbytesread/(DOUBL
		e) pcontentlength);
	The upload progress is saved to session so that Processcontroller.jsp uses request.getsession (). setattribute ("Uploadpercentage", percentage);
} upload.setprogresslistener (new Myprogresslistener (request));
List items = upload.parserequest (request); Iterator ITER = iteMs.iterator ();
  while (Iter.hasnext ()) {Fileitem item = (Fileitem) iter.next ();
    if (Item.isformfield ()) {} else {//string fieldName = Item.getfieldname ();
    String fileName = Item.getname ();
    String ContentType = Item.getcontenttype ();
    System.out.println ();
    Boolean isinmemory = Item.isinmemory ();
    Long sizeinbytes = Item.getsize ();
    File UploadedFile = new file ("c://" + system.currenttimemillis () + filename.substring (Filename.lastindexof ("."));
  Item.write (UploadedFile);
} out.write (' {success:true,msg: ' Save upload file data and analyze Excel success! '} ');
Out.flush (); %>


Processcontroller.jsp:

<%@ page language= "java" import= "java.util.*" ContentType = "Text/html;charset=utf-8" pageencoding= "Utf-8"%> <%//Note that the rise above is necessary.
	Otherwise there will be Ajax garbled problem.
	Remove Uploadpercentage from session and send back to browser Object percent = Request.getsession (). getattribute ("Uploadpercentage");
	String msg = "";
	Double d = 0;
	if (percent==null) {d = 0;
		} else{D = (Double) percent;
	System.out.println ("+++++++processcontroller:" + D);
		} if (d<1) {//d<1 is uploading, msg = "uploading file ...";
	Out.write ("{success:true, msg: '" +msg+ "', Percentage: '" + D + "', Finished:false}"); 
		else if (d>=1) {//d>1 on behalf of upload has ended, start processing analysis Excel,//This example only simulates the processing Excel, places a processexcelpercentage in the session, represents the analysis Excel progress.
		msg = "Processing Excel is being parsed ...";
		String finished = "false";
		Double processexcelpercentage = 0.0;
		Object o = request.getsession (). getattribute ("Processexcelpercentage");
			if (o==null) {processexcelpercentage = 0.0;
			
		Request.getsession (). setattribute ("Processexcelpercentage", 0.0); } else{//Analog processing Excel, percent per passAdd 0.1 processexcelpercentage = (Double) O + 0.1;
			Request.getsession (). setattribute ("Processexcelpercentage", processexcelpercentage);
				if (processexcelpercentage>=1) {//When processexcelpercentage>1 is finished on behalf of Excel.
				Request.getsession (). RemoveAttribute ("Uploadpercentage");
				Request.getsession (). RemoveAttribute ("Processexcelpercentage");
			The client determines whether the end of the flag finished = "true"; } out.write ("{success:true, msg: '" +msg+ ", Percentage: '" + processexcelpercentage + "', Finished:" + Finished + "}")
		;
	Note that the returned data, success represents the state//percentage is a percent//finished represents whether the whole process ends.
} out.flush (); %>


Form page upload.html:

 


Put the three files to tomcat/webapps/root/, and also put the main ext file here, start Tomcat test: http://localhost:8080/upload.html

My resources have a complete sample file: Click to download , download zip file after extracting to tomcat/webapps/root/can be tested.

Finally, special reminders are needed because the FileUpload component of Apache is used, so it is necessary to put Common-fileupload.jar under Root/web-inf/lib.

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.