The requirement source is as follows: Upload a large Excel file to the server. The server parses the Excel file and inserts it into the database one by one. The whole process takes a long time, therefore, after you Click Upload, You need to display a progress bar and update the progress bar in a timely manner based on the data volume received in the background and the processing progress.
Analysis: two components are required in the background, uploadcontroller. JSP is used to receive and process data. It dynamically places the progress information to the session, and another component processcontroller. JSP is used to update the progress bar. After you click "Upload", the form is submitted to uploadcontroller. JSP. At the same time, use js to start an Ajax request to processcontroller. JSP and Ajax update the progress bar with the percentage of progress obtained, and this process is repeated once per second. This is the basic working principle of this example.
The question is, how does the server know the total amount of data received when receiving data? If we write a File Upload Component from scratch, this problem is well solved. The key is that we often use mature components, such as Apache commons fileupload. Fortunately, apache has long thought of this problem, so the reserved interface can be used to obtain the percentage of received data. Therefore, I use Apache commons fileupload to receive uploaded files.
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 "%> <br/> <% <br/> // note that the preceding import jar package is required. <br/> // apache commons fileupload receives uploaded files; <br/> fileitemfactory factory = new diskfileitemfactory (); <br/> servletfileupload upload = new Servletfileupload (factory); <br/> // implement a request because the internal class cannot reference the request. <Br/> class myprogresslistener implements progresslistener {<br/> private httpservletrequest request = NULL; <br/> myprogresslistener (httpservletrequest request) {<br/> This. request = request; <br/>}< br/> Public void Update (long pbytesread, long pcontentlength, int pitems) {<br/> double percentage = (double) pbytesread/(double) pcontentlength); <br/> // Save the upload progress to the session for processcontroller. JSP usage <br/> requ EST. getsession (). setattribute ("uploadpercentage", percentage); <br/>}< br/> upload. setprogresslistener (New myprogresslistener (request); <br/> list items = upload. parserequest (request); <br/> iterator iter = items. iterator (); <br/> while (ITER. hasnext () {<br/> fileitem item = (fileitem) ITER. next (); <br/> If (item. isformfield () {</P> <p >}else {<br/> // string fieldname = item. getfieldname (); <Br/> string filename = item. getname (); <br/> // string contenttype = item. getcontenttype (); <br/> system. out. println (); <br/> Boolean isinmemory = item. isinmemory (); <br/> long sizeinbytes = item. getsize (); <br/> file uploadedfile = new file ("C: //" + system. currenttimemillis () + filename. substring (filename. lastindexof (". "); <br/> item. write (uploadedfile); <br/>}< br/> out. write ("{success: True, MSG: 'The uploaded file data is saved and analyzed in Excel! '} "); <Br/> out. Flush (); <br/>%> <br/>
Processcontroller. jsp:
<% @ Page Language = "Java" Import = "Java. util. * "contenttype =" text/html; charset = UTF-8 "pageencoding =" UTF-8 "%> <br/> <% <br/> // note that the above header is required. Otherwise, Ajax garbled characters may occur. <Br/> // retrieve the uploadpercentage from the session and send it back to the browser <br/> Object percent = request. getsession (). getattribute ("uploadpercentage"); <br/> string MSG = ""; <br/> double D = 0; <br/> If (percent = NULL) {<br/> D = 0; <br/>}< br/> else {<br/> d = (double) percent; <br/> // system. out. println ("++ processcontroller:" + d); <br/>}< br/> If (d <1) {<br/> // d <1 indicates that the file is being uploaded. <br/> MSG = "the file is being uploaded... "; <br/> out. write ("{success: True, MSG :'" + MSG + "', percentage:'" + D + "', finished: false}"); <br/>}< br/> else if (D> = 1) {<br/> // D> 1 indicates that the upload is complete and the analysis Excel file is processed. <br/> // in this example, only the Excel file is simulated and a processexcelpercentage is placed in the session, indicates the progress of Excel analysis. <Br/> MSG = "analysis processing Excel... "; <br/> string finished =" false "; <br/> double processexcelpercentage = 0.0; <br/> Object o = request. getsession (). getattribute ("processexcelpercentage"); <br/> If (O = NULL) {<br/> processexcelpercentage = 0.0; <br/> request. getsession (). setattribute ("processexcelpercentage", 0.0); </P> <p >}< br/> else {<br/> // simulate Excel processing, percentage increases by 0.1 each time <br/> processexcelpercentage = (double) O + 0.1; <br /> Request. getsession (). setattribute ("processexcelpercentage", processexcelpercentage); <br/> If (processexcelpercentage >=1) {<br/> // when processexcelpercentage> 1 indicates that the Excel analysis is complete. <Br/> request. getsession (). removeattribute ("uploadpercentage"); <br/> request. getsession (). removeattribute ("processexcelpercentage"); <br/> // The finished = "true "; <br/>}< br/> out. write ("{success: True, MSG: '" + MSG + "', percentage: '" + processexcelpercentage + "', finished:" + finished + "}"); <br/> // pay attention to the returned data. Success indicates the status. <br/> // percentage indicates the percentage. <br/> // finished indicates whether the entire process is completed. <Br/>}< br/> out. Flush (); <br/>%> <br/>
Upload.html:
<HTML> <br/> <pead> <br/> <meta http-equiv = "Content-Type" content = "text/html; charset = UTF-8 "/> <br/> <title> file upload field example </title> <br/> <LINK rel =" stylesheet "type =" text/CSS "< br/> href = "ext/resources/CSS/ext-all.css"/> <br/> <SCRIPT type = "text/JavaScript" src = "ext/adapter/EXT/ext-base.js"> </SCRIPT> <br/> <SCRIPT type = "text/JavaScript" src = "ext/ext-all.js"> </SCRIPT> <br/> <style> <br/> </sty Le> <br/> </pead> <br/> <body> <br/> <a href = "http://blog.csdn.net/sunxing007"> sunxing007 </a> <br/> <Div id = "form"> </div> <br/> </body> <br/> <SCRIPT> <br/> var fm = new Ext. formpanel ({<br/> title: 'upload Excel file', <br/> URL: 'uploadcontroller. JSP? T = '+ new date (), <br/> autoscroll: True, <br/> applyto: 'form', <br/> Height: 120, <br/> width: 500, <br/> frame: false, <br/> fileupload: True, <br/> defaulttype: 'textfield ', <br/> labelwidth: 200, <br/> items: [{<br/> xtype: 'field', <br/> fieldlabel: 'select the Excel file to upload ', <br/> allowblank: false, <br/> inputtype: 'file', <br/> name: 'file' <br/>}], <br/> buttons: [{<br/> text: 'start upload', <br/> handler: function () {<br/> // click 'Start upload' is processed by this function. <Br/> If (FM. form. isvalid () {// verify form. In this example, the <br/> // display progress bar <br/> Ext. messageBox. show ({<br/> title: 'uploading A file', <br/> // MSG: 'processing... ', <br/> width: 240, <br/> progress: True, <br/> closable: false, <br/> buttons: {cancel: 'cancel'} <br/>}); <br/> // form submitted <br/> FM. getform (). submit (); <br/> // set a timer to send an Ajax request to processcontroller every 500 milliseconds <br/> var I = 0; <br/> var timer = setinterval (function () {<br/> // Request example <br/> Ext. ajax. request ({<br/> // The URL below is critical, I have been debugging for this for a long time <br/> // in the future, any request URL in Ajax must carry a date stamp, <br/> // otherwise, the data may be the same each time. <br/> // This is related to the browser cache. <br/> URL: 'processcontroller. JSP? T = '+ new date (), <br/> method: 'get', <br/> // process Ajax returned data <br/> success: function (response, options) {<br/> Status = response. responsetext + "" + I ++; <br/> var OBJ = ext. util. JSON. decode (response. responsetext); <br/> If (obj. success! = False) {<br/> If (obj. finished) {<br/> clearinterval (timer); <br/> // status = response. responsetext; <br/> Ext. messageBox. updateprogress (1, 'finished', 'finished'); <br/> Ext. messageBox. hide (); <br/>}< br/> else {<br/> Ext. messageBox. updateprogress (obj. percentage, obj. MSG); <br/>}< br/>}, <br/> failure: function () {<br/> clearinterval (timer ); <br/> Ext. MSG. alert ('error', 'is incorrect. '); <Br/>}< br/>}); <br/>}, 500 ); </P> <p >}< br/> else {<br/> Ext. MSG. alert ("message", "select an Excel file before uploading. "); <br/>}< br/>}] <br/> }); <br/> </SCRIPT> <br/> </ptml> <br/>
Put the three files in Tomcat/webapps/root/and put the main ext files here. Start tomcat to test: http: // localhost: 8080/upload.html.
My resources contains the complete example file: http://download.csdn.net/source/1719593, download the ZIP file and decompress it to Tomcat/webapps/root/to test.
Finally, we need a special reminder, because the fileupload component of Apache is used, so we need to put the common-fileupload.jar under root/WEB-INF/lib.