Ajax File Upload progress bar

Source: Internet
Author: User
Tags file upload progress bar tojson

Ajax File Upload progress bar
Preface:
Idea: first, the form is submitted to the servlet, And the servlet is used for file upload. The uploaded parameters are encapsulated into objects and saved to the session. The submitted pages are hidden iframe windows. Then, an ajax asynchronous request is used to obtain the object in the session and convert the object into a json object and output it. When the object status is upload completed or the operation is abnormal, the corresponding properties in the session are cleared. Callback functions of asynchronous operations can be used.
The var jinduStatus = eval (+ xmlHttp. responseText +) method converts json to an object, and then obtains the parameter values in the corresponding json in the form of jinduStatus [xxx] Or jinduStatus. xxx. The callback function then determines whether to continue calling the asynchronous function based on the parameter values returned by the server.
Details:
Easy to ignore:
A) there are multiple file upload controls on the page, but not all of them are filled during submission.
B) the current page is closed during file upload, but the session still exists.1. Required jar packages:
Commons-fileupload-x.x.x.jar
Commons-io-x.x.jar
Ii. upload page: test01.jsp
<% @ Page language = java import = java. util. * pageEncoding = UTF-8 %> <Script type = text/javascript src = js/xmlHttp. js> </script>
<Iframe name = "uploadToPage" none = "" style = "display:"> </iframe>3. Request Upload: js/xmlHttp. js
Var xmlHttp = false; function createXMLHTTPRequest () {try {xmlHttp = new ActiveXObject (Msxml2.XMLHTTP);} catch (e) {try {xmlHttp = new ActiveXObject (Microsoft. XMLHTTP);} catch (ee) {xmlHttp = new XMLHttpRequest () ;}return xmlHttp;} function uploadFileListener () {var upFileForm = document. getElementById (upFileForm); var files = document. getElementsByName (file); var empSelectFile = true; for (var I = 0; I Function changeJindu (percent) {var upPercent = document. getElementById (upPercent); upPercent. innerHTML = percent + %; var fullJinduWidth = document. getElementById (fullJindu ). style. width; var jinduNode = document. getElementById (jindu); var fullJinduVal = parseInt (fullJinduWidth. substring (0, fullJinduWidth. length-2); jinduNode. style. width = (fullJinduVal * percent/100) + 'px ';}
Function testProgress () {var jindu = document. getElementById (jindu); var jinduWidth = jindu. style. width; var jinduWidthVal = jinduWidth. substring (0, jinduWidth. length-2); jindu. style. width = parseInt (jinduWidthVal) + 5 ;}

Iv. Upload processing servlet: FileUpload. java
Package com. wtb. test. ajax. xmlHttp. progress;
Import java. io. file; import java. io. fileOutputStream; import java. io. IOException; import java. io. inputStream; import java. io. printWriter; import java. util. list;
Import javax. servlet. servletException; import javax. servlet. http. httpServlet; import javax. servlet. http. httpServletRequest; import javax. servlet. http. httpServletResponse; import javax. servlet. http. httpSession;
Import org. apache. commons. fileupload. fileItem; import org. apache. commons. fileupload. fileItemFactory; import org. apache. commons. fileupload. disk. diskFileItemFactory; import org. apache. commons. fileupload. servlet. servletFileUpload;
@ SuppressWarnings (serial) public class FileUpload extends HttpServlet {public void doGet (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {doPost (request, response );} public void doPost (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {request. setCharacterEncoding (UTF-8); response. setCharacterEncoding (UT F-8); HttpSession session = request. getSession (); PrintWriter out = response. getWriter (); if (running. equals (request. getParameter (reading) {Status status Status = (Status) session. getAttribute (statusSession); if (1. equals (request. getParameter (requestCount) {// The first request if (status! = Null) {if (status. getShowFlag () = 1) {session. removeAttribute (statusSession) ;}} else {if (status! = Null) {if (status. getShowFlag () = 1) {session. removeAttribute (statusSession) ;}}if (status = null) {status = new Status ();} out. print (status. toJson (); out. close ();} else {// Upload File // create the file project factory object FileItemFactory factory = new DiskFileItemFactory (); // use the factory to instantiate the Upload Component, servletFileUpload: resolution File upload request ServletFileUpload upload = new ServletFileUpload (factory); // creation progress Status object status = new Status (); try {session. setAttribute (upFileFinish, 0); // put the parsing result into the List FileItemList = upload. parseRequest (request); status. setRetMsg (calculate the file size ...); session. setAttribute (statusSession, status); // calculate the total size of the file to be uploaded and put it into the status object. Long totalSize = 0; for (FileItem fileItem: fileItemList) {if (! FileItem. isFormField () {// file field totalSize + = fileItem. getSize () ;}} status. setTotalSize (totalSize); status. setRetMsg (total file size: + totalSize + bytes, start to upload the file ...); string totalPercent = 0.00; status. setTotalPercent (0.00); status. setFilePercent (0.00); System. out. println (status. getRetMsg (); session. setAttribute (statusSession, status); long totalWriteSize = 0; for (FileItem fileItem: fileItemList) {if (fileItem. isFormField () {// text field // obtain the form name The value of the name attribute. This method is also applicable to the file field String fieldName = fileItem. getFieldName (); String value = fileItem. getString (); // get the content of the text field. This method does not apply to the file field System. out. println (fieldName +: + value);} else {// file domain // obtain the Upload File Name String filePath = fileItem. getName (); if (!. Equals (filePath) {String fileName = filePath. substring (filePath. lastIndexOf (\) + 1); // obtain the file data input stream InputStream in = fileItem. getInputStream (); // sets the File Upload path String upFileDir = this. getServletContext (). getRealPath (/uploadFile); // sets the progress state long fileSize = fileItem. getSize (); status. setFileSize (fileSize); status. setContextType (fileItem. getContentType (); status. setState (1); status. setShowFlag (0); // create a file output stream FileOutputStream fos = new FileOutputStream (new File (upFileDir, fileName); byte [] B = new byte [1024]; int len = 0; long fileWriteSize = 0; String filePercent = 0.00; while (len = in. read (B ))! =-1) {fos. write (B, 0, len); totalWriteSize + = len; fileWriteSize + = len; status. setTotalWriteSize (totalWriteSize); status. setFileWriteSize (fileWriteSize); filePercent = String. format (%. 2f, (double) fileWriteSize) * 100/fileSize); totalPercent = String. format (%. 2f, (double) totalWriteSize) * 100/totalSize); status. setFilePercent (filePercent); status. setTotalPercent (totalPercent); status. setRetMsg (uploading + fileName +; progress of a single file: + filePercent + %; overall progress: + totalPercent + % .); // System. out. println (status. getRetMsg (); session. setAttribute (statusSession, status);} in. close (); fos. close () ;}} status. setState (2); status. setRetMsg (the file is uploaded successfully); status. setShowFlag (1); System. out. println (status. getRetMsg (); session. setAttribute (statusSession, status);} catch (Exception e) {e. printStackTrace (); status. setState (3); status. setRetMsg (File Upload exception); status. setShowFlag (1); session. setAttribute (statusSession, status );}}}
}
5. servlet corresponds to the web. xml file:
FileUpload Com. wtb. test. ajax. xmlHttp. progress. FileUpload
FileUpload /Servlet/FileUpload Index. jsp 6. File Upload Status: Status. java
Package com. wtb. test. ajax. xmlHttp. progress;
Public class Status {private long totalSize; // The total size of the uploaded file private long fileSize; // The current file size private long totalWriteSize; // The total size of the written bytes private long fileWriteSize; // The current file is written into the byte private int state; // The current state is: 0: not uploaded; 1: Uploading in progress; 2: the upload is complete; 3: An exception occurs during the upload. Private String retMsg; // description private int showFlag; // whether to continue reading progress. 0: Read progress; 1: Stop the upload operation private String contextType; // The current file type private String filePercent; // The percentage of private String totalPercent uploaded to a single file; // total upload percentage public Status () {setRetMsg (); setContextType (); setFilePercent (0.00); setTotalPercent (0.00);} public long getTotalSize () {return totalSize ;} public void setTotalSize (long totalSize) {this. totalSize = totalSize;} public long getFileSize () {return fileSize;} public void setFileSize (long fileSize) {this. fileSize = fileSize;} public long getTotalWriteSize () {return totalWriteSize;} public void setTotalWriteSize (long totalWriteSize) {this. totalWriteSize = totalWriteSize;} public long getFileWriteSize () {return fileWriteSize;} public void setFileWriteSize (long fileWriteSize) {this. fileWriteSize = fileWriteSize;} public int getState () {return state;} public void setState (int state) {this. state = state;} public String getRetMsg () {return retMsg;} public void setRetMsg (String retMsg) {this. retMsg = retMsg;} public int getShowFlag () {return showFlag;} public void setShowFlag (int showFlag) {this. showFlag = showFlag;} public String getContextType () {return contextType;} public void setContextType (String contextType) {this. contextType = contextType;} public String getFilePercent () {return filePercent;} public void setFilePercent (String filePercent) {this. filePercent = filePercent;} public String getTotalPercent () {return totalPercent;} public void setTotalPercent (String totalPercent) {this. totalPercent = totalPercent;} public String toJson () {return {otalSize: + totalSize +, ileSize: + fileSize +, otalWriteSize: + totalWriteSize +, + ileWriteSize: + fileWriteSize +, state: + state +, etMsg: + retMsg +, showFlag: + showFlag +, contextType: + contextType +, ilePercent: + filePercent +, otalPercent: + totalPercent + };}} 7. Create an uploadFile folder under the WebRoot directory to store uploaded files.

========================================================== ========================================================== =

If the JQuery file is imported, the jsp page and js page are as follows, and other pages do not need to be modified.
The implementation page is as follows:
1. Put the jquery-1.9.1.js file under the WebRoot/js directory.
Ii. Page display (test02.jsp): (compared with test01.jsp, The jquery file is introduced and js/xmlHttp. js is changed to js/jqAjax. js)
<% @ Page language = java import = java. util. * pageEncoding = UTF-8 %> <Script type = text/javascript src = js/jquery-1.9.1.js> </script> <script type = text/javascript src = js/jqAjax. js> </script>
<Iframe name = "uploadToPage" none = "" style = "display:"> </iframe> 3. js/jqAjax. js
Function uploadFileListener () {var files = $ (input [type = 'file']); var emp = true; for (var I = 0; I Function changeProgress (percent) {percent (%uppercent).html (percent + %); percent (%jindu).css ({width :( $ (# fullJindu). width () * percent/100) + px });}


 



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.