Ajax implementation of file upload with progress bar

Source: Internet
Author: User


JSP part: Design a form, the properties of the form add enctype= "Multipart/form-data", design an iframe, set to hide. The target of the form equals the name of the IFRAME;


Servlet part: File upload with the commons-fileupload, need two jar,commons-fileupload and Commons-io, less the second will be reported to find the exception of the class;

The first servlet handles the upload, saves the upload progress to the session, and the second servlet processes the AJAX request, returning the session's saved progress value;


Progress bar: You can use Ajax to get back the progress of the value, change the width of the image to achieve change;


JSP Code:

<%@ page language= "java" contenttype= "text/html; Charset=utf-8 "pageencoding=" UTF-8 "%><! DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en" "Http://www.w3.org/TR/html4/loose.dtd" >

This is the code in INDEX.JSP:

After the submission also on the current page display progress, so to use the IFRAME, submitted after the return to the hidden IFrame, does not affect the page effect;


CSS code:

. Pro{height:15px;width:500px;background: #FFFFF0; border:1px solid #8FBC8F; margin:0;padding:0;display:none; Position:relative;left:25px;float:left;}

JS Code


function Go () {f1.submit ();d Ocument.getelementbyid ("Pro"). Style.display= "Block";d Ocument.getelementbyid ("prop"). Style.display= ""; Timer=setinterval ("Getp ()", 50);} var xmlhttprequest;function getp () {if (window. XMLHttpRequest) {xmlhttprequest=new XMLHttpRequest ();} Else{xmlhttprequest=new ActiveXObject ("Microsoft.XMLHTTP");} Xmlhttprequest.onreadystatechange=callback;url= "Getprogressservlet"; Xmlhttprequest.open ("Post", url,true); Xmlhttprequest.setrequestheader ("Content-type", "application/x-www-form-urlencoded"); XmlHttpRequest.send ("& Timestamp= "+ (new Date ()). GetTime ()); Callback functions function CallBack () {if (xmlhttprequest.readystate==4 && xmlhttprequest.status==200) {result= Xmlhttprequest.responsetext;var Result=result.replace (/(^\s*) | ( \s*$)/g, ""); var res=result.split (","); var flag=res[1];var per=parseint (Res[0]); var err=res[2]; document.getElementById ("Imgpro"). style.width=per*5+ "px";d Ocument.getelementbyid ("prop"). innerhtml=per+ "%"; if ( flag== "OK") {Window.clearinterval (timer); alert ("Upload successful! ");d OCUment.getelementbyid ("Pro"). style.display= "None";d Ocument.getelementbyid ("prop"). innerhtml= ""; F1.reset ();} if (err!= "" | | err.length>0) {window.clearinterval (timer); alert (err);} if (flag==null) {window.clearinterval (timer);}}}

Flag for upload success tag, err for error mark;


Servlet code (Uploadservlet):

Package Com.ul.servlet;import Java.io.file;import Java.io.fileoutputstream;import java.io.ioexception;import Java.io.inputstream;import Java.io.printwriter;import Java.util.iterator;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.disk.diskfileitemfactory;import Org.apache.commons.fileupload.servlet.servletfileupload;public class Uploadservlet extends HttpServlet {protected void Doget (HttpServletRequest request, httpservletresponse response) throws Servletexception, IOException {doPost ( request, response);} protected void DoPost (HttpServletRequest request, httpservletresponse response) throws Servletexception, IOException {/ /Set the encoding format to utf-8request.setcharacterencoding ("Utf-8"); Response.setcharacterencoding ("Utf-8");//Get session, save progress and uploadAs a result, the initial value of the upload result is NOK, when the upload is completed httpsession session=request.getsession () session.setattribute ("prog", "0"); Session.setattribute ("Result", "NOK"); Session.setattribute ("Error", ""); String error= "";//Set a maximum value for the uploaded file, here is not more than 50MBint maxsize=50*1024*1024;//Create factory object and File upload object Diskfileitemfactory factory=new Diskfileitemfactory (); Servletfileupload upload=new servletfileupload (factory); try {//Parse upload request list items=upload.parserequest (request); I Terator Itr=items.iterator (); while (Itr.hasnext ()) {Fileitem item= (Fileitem) itr.next ();//Determine if the file domain if (! Item.isformfield ()) {if (Item.getname ()!=null&&!item.getname (). Equals ("")) {//Get upload file size and file name long upfilesize =item.getsize (); String filename=item.getname (); if (upfilesize>maxsize) {error= "The file you uploaded is too large, please select No more than 50MB files!"; break;} At this point the file is temporarily in memory of the server, construct the temporary object file Tempfile=new file (fileName),//Specify the directory and file name of the file upload server, "F:\\temp" Tempfile.getname ());//construct input stream read file InputStream is=item.getinputstream (); int length=0;byte[] by=new byte[1024];d ouble persent=0; FileOutputStream fos=new FileoutPutstream (file); PrintWriter Out=response.getwriter (); while ((Length=is.read (by))!=-1) {//Calculate file Progress persent+=length/(double) upfilesize *100d;fos.write (by, 0, length), Session.setattribute ("prog", Math.Round (persent) + ""); Thread.Sleep (10);} Fos.close (); Thread.Sleep (1000);} Else{error= "did not choose to upload files! ";}}}} catch (Exception e) {e.printstacktrace (); error= "An error occurred while uploading the file:" +e.getmessage ();} if (!error.equals (")") {Session.setattribute ("error", error);} Else{session.setattribute ("Result", "OK");}}}

Don't forget the Commons-io bag



Servlet code (Getprogressservlet):

Package Com.ul.servlet;import Java.io.ioexception;import Java.io.printwriter;import javax.servlet.ServletException ; Import Javax.servlet.http.httpservlet;import Javax.servlet.http.httpservletrequest;import Javax.servlet.http.httpservletresponse;import Javax.servlet.http.httpsession;public class GetProgressServlet Extends HttpServlet {protected void doget (HttpServletRequest request, httpservletresponse response) throws Servletexception, IOException {doPost (request, response);} protected void DoPost (HttpServletRequest request, httpservletresponse response) throws Servletexception, IOException { Request.setcharacterencoding ("Utf-8"); Response.setcharacterencoding ("Utf-8"); HttpSession sesson=request.getsession (); PrintWriter Out=response.getwriter (); String str= (String) sesson.getattribute ("prog") + ""; String res= (String) sesson.getattribute ("result"); String err= (String) sesson.getattribute ("error"); System.out.println (str+ "," +res+ "," +err "), Out.print (str+", "+res+", "+err"; Out.flush (); Out.close ();}}


















Ajax implementation of file upload with progress bar

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.