Use jsp + Extjs to dynamically display the File Upload progress

Source: Internet
Author: User

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:
Copy codeThe Code is as follows:
<% @ 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 preceding import jar package is required
// Use apache commons fileupload to receive uploaded files;
FileItemFactory factory = new DiskFileItemFactory ();
ServletFileUpload upload = new ServletFileUpload (factory );
// Implement a request because the internal class cannot reference the request.
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/(double) pContentLength );
// Save the upload progress to the session for processController. jsp to use
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: 'the uploaded file data is saved and analyzed in Excel! '}");
Out. flush ();
%>

ProcessController. jsp:
Copy codeThe Code is as follows:
<% @ Page language = "java" import = "java. util. *" contentType = "text/html; charset = UTF-8" pageEncoding = "UTF-8" %>
<%
// Note that the above header is required. Otherwise, ajax garbled characters may occur.
// Retrieve uploadPercentage from the session and send it back to the 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 indicates that the file is being uploaded,
Msg = "uploading file ...";
Out. write ("{success: true, msg: '" + msg + "', percentage: '" + d + "', finished: false }");
}
Else if (d> = 1 ){
// D> 1 indicates that the upload is complete and the analysis excel file is processed,
// This example only simulates the processing of excel, and places a processExcelPercentage in the session to represent the progress of the analysis of excel.
Msg = "Processing Analysis Excel ...";
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 {
// Simulate excel processing. The percentage increases by 0.1 each time
ProcessExcelPercentage = (Double) o + 0.1;
Request. getSession (). setAttribute ("processExcelPercentage", processExcelPercentage );
If (processExcelPercentage> = 1 ){
// When processExcelPercentage> 1, the analysis is completed in excel.
Request. getSession (). removeAttribute ("uploadPercentage ");
Request. getSession (). removeAttribute ("processExcelPercentage ");
// The end flag of the Client
Finished = "true ";
}
}
Out. write ("{success: true, msg: '" + msg + "', percentage: '" + processExcelPercentage + "', finished:" + finished + "}");
// Pay attention to the returned data. success indicates the status.
// Percentage is the percentage
// Finished indicates whether the entire process is complete.
}
Out. flush ();
%>

Upload.html:
Copy codeThe Code is as follows:
<Html>
<Head>
<Meta http-equiv = "Content-Type" content = "text/html; charset = UTF-8"/>
<Title> File Upload Field Example </title>
<Link rel = "stylesheet" type = "text/css"
Href = "ext/resources/css/ext-all.css"/>
<Script type = "text/javascript" src = "ext/adapter/ext/ext-base.js"> </script>
<Script type = "text/javascript" src = "ext/ ext-all.js"> </script>
<Style>
</Style>
</Head>
<Body>
<A href = "http://blog.csdn.net/sunxing007"> sunxing007 </a>
<Div id = "form"> </div>
</Body>
<Script>
Var fm = new Ext. FormPanel ({
Title: 'upload an excel file ',
Url: 'uploadcontroller. jsp? T = '+ new Date (),
AutoScroll: true,
ApplyTo: 'form ',
Height: 120,
Width: 500,
Frame: false,
FileUpload: true,
DefaultType: 'textfield ',
LabelWidth: 200,
Items :[{
Xtype: 'field ',
FieldLabel: 'select the Excel file to upload ',
AllowBlank: false,
InputType: 'file ',
Name: 'file'
}],
Buttons :[{
Text: 'start upload ',
Handler: function (){
// After you click Start upload, this function will process the upload.
If (fm. form. isValid () {// verify form. This example is omitted.
// Display the progress bar
Ext. MessageBox. show ({
Title: 'uploading A file ',
// Msg: 'processing ...',
Width: 240,
Progress: true,
Closable: false,
Buttons: {cancel: 'cancel '}
});
// Form submission
Fm. getForm (). submit ();
// Set a timer to send an ajax request to processController every 500 milliseconds
Var I = 0;
Var timer = setInterval (function (){
// Request example
Ext. Ajax. request ({
// The url below is very important. I have been debugging it for a long time.
// In the future, any url in the ajax request must carry a date stamp,
// Otherwise, it is very likely that the data will be the same each time,
// This is related to browser cache
Url: 'processcontroller. jsp? T = '+ new Date (),
Method: 'get ',
// Process ajax returned data
Success: function (response, options ){
Status = response. responseText + "" + I ++;
Var obj = Ext. util. JSON. decode (response. responseText );
If (obj. success! = False ){
If (obj. finished ){
ClearInterval (timer );
// Status = response. responseText;
Ext. MessageBox. updateProgress (1, 'finished', 'finished ');
Ext. MessageBox. hide ();
}
Else {
Ext. MessageBox. updateProgress (obj. percentage, obj. msg );
}
}
},
Failure: function (){
ClearInterval (timer );
Ext. Msg. alert ('error', 'an error occurs. ');
}
});
},500 );

}
Else {
Ext. Msg. alert ("message", "select an Excel file before uploading .");
}
}
}]
});
</Script>
</Html>

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 contain a complete example file:Click to downloadDownload the zip file and decompress it to tomcat/webapps/ROOT.

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.
 

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.