jQuery file upload progress bar without flash
June 30, 2010 20:14:28 Last update: July 03, 2010 18:41:12
- The HTML page
<!DOCTYPE html> <html> <head> <title>jQuery File Upload without Flash</title> <link rel="stylesheet" type="text/css" media="all" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.2/themes/ui-darkness/jquery-ui.css"/> <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"> </script> <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.2/jquery-ui.min.js"> </script> </head> <body> <form action="uploadFile.do" enctype="multipart/form-data" method="POST" onsubmit="startUpload();"> <input type="file" name="theUploadFile"> <input type="submit" name="submit" value="Upload"> </form> <div id="progress-bar"></div> </body> </html>
- Client Side Code
// called before upload submit function startUpload() { $('#progress-bar') .progressbar() .data('uploadCompleted', false); window.setTimeout(uploadProgress, 1000); } // called every one second. Server side url uploadProgress.do returns // text: <bytes uploaded so far>/<file size>, e.g.: '1325/33387' function uploadProgress() { if ($('#progress-bar').data('uploadCompleted')) { $('#progress-bar').progressbar('destroy'); return; } $.ajax({ url: 'uploadProgress.do', cache: false, // this is important, otherwise there's no progress in IE! success: function(response) { var s = response.split('/'); $('#progress-bar').progressbar( 'option', 'value', 100*s[0]/s[1] ); } }); window.setTimeout(uploadProgress, 1000); } // called when file upload is done. Only useful for ajax type uploads function completeUpload() { $('#progress-bar').data('uploadCompleted', true); }
- Server Side Code
Using Apache Commons FileUpload as example.
Upload code (responds tofileUpload.do):final HttpSession session = httpServletRequest.getSession(); ServletFileUpload servletFileUpload = new ServletFileUpload( new DiskFileItemFactory() ); servletFileUpload.setProgressListener(new ProgressListener() { private long megaBytes = -1; public void update(long bytesRead, long totalBytes, int nItem) { long mBytes = bytesRead >> 20; if ((megaBytes != mBytes) || (bytesRead == totalBytes)) { megaBytes = mBytes; session.setAttribute("fileUploadTotalBytes", "" + totalBytes); session.setAttribute("fileUploadBytesRead", "" + bytesRead); } } }); List fileItems = servletFileUpload.parseRequest(request); . . .
Progress code (responds touploadProgress.do):HttpSession session = httpServletRequest.getSession(); httpServletResponse.setContentType("text/plain"); ServletOutputStream out = httpServletResponse.getOutputStream(); out.print( session.getAttribute("fileUploadBytesRead") + "/" + session.getAttribute("fileUploadTotalBytes") ); out.close();