Implement file upload and display progress bar _javascript technique based on Ajax

Source: Internet
Author: User
Tags sleep

Below to share under the AJAX implementation of the file upload and display progress bar. In the JSP section, you need to design a form that adds enctype= "Multipart/form-data" to the form's properties, and designs an iframe as hidden. The target of the form equals the name of the IFRAME;

In the servlet section: File upload with the commons-fileupload, need two jar,commons-fileupload and Commons-io, less the second will report the exception that cannot find the class;

The first servlet handles uploads, and the upload progress is saved to session, and the second servlet handles the AJAX request, returning the progress value of the session save;

Progress bar: You can use Ajax to get the progress value of the return, change the width of the picture 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 the index.jsp:

After the submission of the current page shows progress, so to use the IFRAME, submitted back to the hidden iframe, do not affect the page effect;

CSS code:

Copy Code code as follows:

. 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 ();
 document.getElementById ("Pro"). style.display= "Block";
 document.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=XMLH
  Ttprequest.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"; document.getElementById ("PROp "). innerhtml=per+"% ";
   if (flag== "OK") {Window.clearinterval (timer); Alert ("Upload success!")
   ");
   document.getElementById ("Pro"). style.display= "None";
   document.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 mark, err is 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 R 
 Esponse) throws Servletexception, IOException {doPost (request, response); 
  } protected void DoPost (HttpServletRequest request, httpservletresponse response) throws Servletexception, IOException {
  Set the encoding format to Utf-8 request.setcharacterencoding ("Utf-8"); Response.setchAracterencoding ("Utf-8");
  Get session, save progress and upload results, upload results initial value for NOK, when OK for upload complete 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, which is not exceeding 50MB int maxsize=50*1024*1024;
  Create factory objects and file upload objects Diskfileitemfactory factory=new diskfileitemfactory ();
  Servletfileupload upload=new servletfileupload (Factory);
   try {//Parse upload requests List items=upload.parserequest (request);
   
   Iterator Itr=items.iterator ();
    while (Itr.hasnext ()) {Fileitem item= (Fileitem) itr.next (); Determines whether the file domain if (!item.isformfield ()) {if (Item.getname ())!=null&&!item.getname (). Equals ("")) {//Get uploaded file large   
      Small 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 file!";
      Break
      ///This time the file exists in the server's memory, constructs the temporary object file Tempfile=new file (fileName); Specify the textThe directory and file name of the upload server ("F:\\temp", Tempfile.getname ()) file=new files;
      Constructs input stream read file InputStream is=item.getinputstream ();
      int length=0;
      Byte[] By=new byte[1024];
      Double persent=0;
      FileOutputStream fos=new fileoutputstream (file);
      PrintWriter Out=response.getwriter ();
       while ((Length=is.read (by))!=-1) {//Computed 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= "Upload file Error:" +e.getmessage ();
  } if (!error.equals ("")) {Session.setattribute ("error", error);
  }else{Session.setattribute ("result", "OK");

 }
 }
}

Don't forget 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, HTTPSERVLETRESPO
 NSE 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 ();


 }

}

The effect chart is as follows:

The above is the entire content of this article, I hope to help you.

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.