非阻塞异步处理。敬请高人指点,不胜感激。

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
/c:set
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">







555-555

.a{float:left;width:120px;height:150px;border:0px solid green;margin-left:15px;margin-top:15px;} .img{width:120px; height:150px;z-index:1;border-radius:7px;} .bottom{width:100%;height:22px;border:0px solid red; position:relative; left:0px;bottom:42px; z-index:2; background:#696969 ;} #x{width:16px;height:19px;border:0px solid red; position:relative; z-index:2; left:47px;} #a2{width:16px;height:19px;border:0px solid red; position:relative; z-index:2; left:47px;} .xx{width:16px;height:19px;margin-left:0px;margin-top:-18px;} #pn{width:85px;height:18px;border:0px solid red;margin-left:4px; margin-top:-16px;float:left; z-index:2; } #wap{margin :0px auto; width:990px;height:auto;border:1px solid red;} #dd{ width:990px;height:180px;border:1px solid red;background:#FFA488;} #b1{ width:80px;height:25px;} #b2{ width:80px;height:25px;margin-left:30px;} body{background:#87CEFA;} .p1{position:relative;z-index:2;} .b{height:100%;width:0px;background:green;float:left;} .z1{height:100%;width:100%;float:left; position:relative; left:0px; bottom:18px; z-index:-2;} .s {width:100%; height:18px;border:1px solid #778899;position:relative;left:0px;bottom:80px; z-index:2; visibility:hidden;} <p></head><br> <body><br> <center><br> <div id="wap"><br> &lt;%--<br> <input id="doc" type="file" name="file" multiple="true" style="width:150px;" accept="image/*"><br> --%&gt;<br> <input id="doc" type="file" name="file" multiple="true" style="width:150px;"><br> <div id="dd"></div><br> </div><br> <input id="b1" onclick="javascript:$.uplos();" type="submit" value="开始上传"><br> <button id="b2" onclick="javascript:$.d();">取消上传</button><br> </center><br> </body></html></p>

package com.servlet;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.List;
import java.util.Random;

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.ProgressListener;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import sun.management.counter.Variability;

import com.dao.PicDAO;
import com.entity.Picture;
import com.entity.User;
import com.listner.UploadProgress;
import com.listner.UserProperties;

public class UploadServlet extends HttpServlet {
private static final long serialVersionUID = 1L;

public UploadServlet() {
    super();
}

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    this.doPost(request, response);
}

private  PicDAO picDAO = new PicDAO();
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    response.setContentType("text/html");
    response.setCharacterEncoding("UTF-8");
    String methodName = request.getParameter("method");
        try {
            Method method = getClass().getDeclaredMethod(methodName, HttpServletRequest.class,HttpServletResponse.class);
            method.setAccessible(true);
            method.invoke(this,request,response);
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e);      
        }
}
protected void uploadAjax3(HttpServletRequest request, HttpServletResponse response) throws Exception{
    response.setContentType("text/xml;charset=UTF-8"); 
    DiskFileItemFactory factory = new DiskFileItemFactory();
    ServletFileUpload upload = new ServletFileUpload(factory);
    upload.setHeaderEncoding("UTF-8");

    List<FileItem> items = upload.parseRequest(request);

    String fileMaxSize = UserProperties.getInstance().getProperty("fileMaxSize");
    String totleFileMaxSize = UserProperties.getInstance().getProperty("totalFileMaxSize");
    upload.setSizeMax(Integer.parseInt(totleFileMaxSize));
    upload.setFileSizeMax(Integer.parseInt(fileMaxSize));

// HttpSession session = request.getSession();
// User user = (User) session.getAttribute("user");
long id3 = 10;

//  long id3 = Long.parseLong(request.getParameter("id3"));

// response.setHeader("Cache-Control","no-cache");
// PrintWriter pw = response.getWriter();
String name = request.getParameter("name");
System.out.println(name);
for (FileItem item : items) {
if (item.isFormField()) {
String value = item.getString();
}else{
String pathP = UserProperties.getInstance().getProperty("url");
File file = new File(pathP + "/" + "pic_" + id3);
if (!file.exists()) {
file.mkdirs();
}else{
String picName = item.getName();
picName = picName.substring(picName.lastIndexOf("/") + 1);

String exts = picName.substring(picName.lastIndexOf("."));
String exts2 = picName.substring(picName.lastIndexOf(".") + 1);
String extsName = UserProperties.getInstance().getProperty("extsName");
List extsN = Arrays.asList(extsName.split(","));

                InputStream in = null;
                FileOutputStream fos = null;
                try {/*
                    if (!extsN.contains(exts2)) {
                        pw.print("a1");
                        pw.flush();
                        return;
                    }else{
                        if (item.getSize() == 0 || item.getSize() > upload.getFileSizeMax()) {
                            pw.print("a2");
                            pw.flush();
                            return;
                        }else{*/

                    //      pw.print("a3");         
                    //      totalSize = request.getContentLength();
                            Random random = new Random();
                            int randomNuber = random.nextInt(1000);
                            String tmpPath = pathP + "/"  + "pic_" + id3 + "/" + System.currentTimeMillis() + randomNuber + exts;

                            b = item.getSize();                             

                            String s = b + name;
                            System.out.println(s + "ff");

                            in = item.getInputStream();
                            fos = new FileOutputStream(new File(tmpPath));
                            byte[] buffer = new byte[1024]; 
                            int n;
                            a = 0L;                             
                            while ((n = in.read(buffer)) != -1) { 
                                fos.write(buffer, 0, n);
                                a += (long) n;  }   
                            fos.flush();   
                            fos.close();
                            in.close();                                                                                     
                            item.delete();      // 内存中删除该数据流  
                            Picture picture = new Picture();
                            picture.setPicName(picName);
                            picture.setPicUrl(tmpPath);
                            picture.setUserId(id3);
                            picDAO.sava(picture);
                //          pw.flush();
            //          }
            //      }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

protected void status(HttpServletRequest request,HttpServletResponse response) throws IOException {
    response.setContentType("text/xml");
    response.setHeader("Cache-Control","no-cache"); 
    System.out.println("来自servletrrrrrrrrrrrrrrr");
    try {
        if (a == 0 && b == 0) {
            int percent = 0;
            response.getWriter().print(percent);
            response.getWriter().flush();
        }else 
        if (b > 0 && b > a) {
            int percent = (int) (a * 100 /b);         
            response.getWriter().print(percent);
            response.getWriter().flush();
        }else if (b > 0 && a > 0 && b== a) {
            int percent = 100;
            response.getWriter().print(percent);
            response.getWriter().flush();
            b = 0L;a = 0L;
        }
    } catch (Exception e) {         
        e.printStackTrace();
    }
}   
  private long a = 0L;
  private long b = 0L;

}

  $.extend({
      creatXMLhttp:function(){
          if(window.ActiveXObject){
              xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
          }
          else{
              xmlHttp = new XMLHttpRequest();
          } }  });
/*  $.extend({
      callback:function(g){
       if (xmlHttp.readyState == 4) {           
        if(xmlHttp.status == 200 || xmlHttp.status == 0) {
          var b = xmlHttp.responseText;             //var b2 = JSON.parse(xhr.responseText);var b1 = xhr.responseXML;                                 
    //    var t = ob.name;                
          var o = $("div[title='"+ g +"']").attr("id");           
          var a = $("#" + o).parent().attr("id");
          var bottom = $("#" + o).next().attr("id");
           $("#" + a).removeAttr("onmouseover");
           $("#" + a).removeAttr("onmouseout");
           $("#"+ bottom).attr("style","visibility:visible");
          var xx =  $("#" + bottom).children().next().children().attr("id");
           $("#" + xx).removeAttr("onclick");              
         if(b == 'a1' || b == 'a2'){                    
            $("#" + xx).attr("src","xx7.png");
              return true;
          }else 
         if(b == 'a3'){ 
            $("#" + xx).attr("src","aaa.png");
            return true;
         }
        }
        else{
            alert("上传失败!");
        }
       }
      }
  });*/

  $.extend({
     uplos:function(){  
       var fileMuls = $("#doc").get(0).files;      //var fileMul = document.getElementById("doc"); //      var fileMuls = fileMul.files;
       $(".s").attr("style","visibility:visible");
       $(".b").attr("style","width:0%");   
       $.each(fileMuls,function(i,ob){ 
             $.uploaz(ob);
       });
     }
  });              
  var xmlHttp = null;     
  $.extend({
      uploaz:function(ob){
        $.creatXMLhttp();   
        var g = ob.name;
        var urla = "/k-08/upload?method=uploadAjax3";
        var url = urla + "&timestamp="+ parseInt(10000*Math.random())+ "&name="+ g;     
        xmlHttp.open("POST",url,true);        //异步:true;同步:false
        var fd = new FormData();   
        fd.append("img",ob);           
        xmlHttp.send(fd);
    //  xmlHttp.onreadystatechange = $.callback(g);
        $.ajaxSend(g);
      }
  });

    $.extend({
        ajaxSend:function(g){
            $.creatXMLhttp();
            var urlb = "/k-08/upload?method=status";
            var urls = urlb + "&timestamp="+ parseInt(10000*Math.random()) + "&name=" + g;  
            xmlHttp.open("POST",urls,false);    
            xmlHttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded"); 
            xmlHttp.send();
            xmlHttp.onreadystatechange = $.handler(g);
        }
    });
    $.extend({
        handler:function(g){
         if(xmlHttp.readyState == 4){
            if(xmlHttp.status == 200 || xmlHttp.status == 0){
                var percent = xmlHttp.responseText;     

            //  var percent = answer.substring(0,answer.indexOf('.'));
            //  var name = answer.substring(answer.indexOf('.')+ 1,answer.length);
                //      alert(name);            
            //  if(name == g){              
                var o = $("div[title='"+ g +"']").attr("id");             
                var z = $("#" + o).children().attr("id");
                var u = $("#" + o).children().next().children().attr("id");   
                $("#" + u).attr("style","width:"+ parseInt(percent) + "%");
                $("#" + z).html(+ percent +"%");
                var fileMuls = $("#doc").get(0).files;                  
                if(percent == 0 && fileMuls.length !== 0){                  
                   setTimeout("$.ajaxSend('"+g+"')",300);                                                           
                }else
                if(percent > 0 && percent < 100){
                   setTimeout("$.ajaxSend('"+g+"')",300);                       
                }else    
                if(percent == 100){
              var o = $("div[title='"+ g +"']").attr("id");           
              var a = $("#" + o).parent().attr("id");
              var bottom = $("#" + o).next().attr("id");
               $("#" + a).removeAttr("onmouseover");
               $("#" + a).removeAttr("onmouseout");
               $("#"+ bottom).attr("style","visibility:visible");
              var xx =  $("#" + bottom).children().next().children().attr("id");
               $("#" + xx).removeAttr("onclick");              
               $("#" + xx).attr("src","aaa.png");                       

/**************************************************************************/

                   return true;
                }else 
                if(percent > 100){
                   com.attr("style","width:100%");
                   return false;
                }else 
                if(percent == 0 && fileMuls.length == 0){
                   return false;
                }                                       
            }
         }
         return true;
        }
    //  }
    });