精华内容
下载资源
问答
  • java进度条异步上传,采用servlet、ajax 可以用来学习交流使用
  • 转载自:http://blog.sina.com.cn/s/blog_6a5fb6e10100l60o.html http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> http://www.w3.org/1999/xhtml"> 一亩三分-上传 ...var totalByte=[0,0

    转载自:http://blog.sina.com.cn/s/blog_6a5fb6e10100l60o.html

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
    <title>一亩三分-上传</title>
    <SCRIPT src="/1m3f/Common_Development/Global.js"></SCRIPT>
    <SCRIPT src="/1m3f/Common_Development/HttpSubmit.js"></SCRIPT>
    <SCRIPT src="/1m3f/Common_Development/Tools.js"></SCRIPT>
    <script language="javascript">...
       
    var totalByte=[0,0];
    var uploadedByte=[0,0];
    var halder=[];
    var uploadForms=[];
    //var totalBar=[];
    var goBar=[];
    var rightfulExts=...{};
    rightfulExts.rar="";
    rightfulExts.jpg="";
    rightfulExts.exe="";
    rightfulExts.iso="";
    rightfulExts.gif="";
    rightfulExts.ini="";
    rightfulExts.rmvb="";
    rightfulExts.pdf="";
    var formCount=-2;

    function upload()...{
        formCount++;
        if(formCount<0||formCount>1)...{
            return false;
        }
       
        var ext=uploadForms[formCount].fileData.value.split(".").pop().toLowerCase();
        if(!(ext in rightfulExts)&&ext!="")...{
            alert("第"+(formCount+1)+"个文件类型不匹配!");
            return false;
        }
        if(ext!="")...{
            uploadForms[formCount].saveName.value=getNewId("13","fileUpload13")+"."+ext;
        }
       
        uploadForms[formCount].curCount.value=formCount;
        uploadForms[formCount].submit();
       
        totalByte[formCount]=0;
        halder[formCount]=window.setInterval("getTotalByte("+formCount+");",1);
    }

    function getTotalByte(c)...{
        totalByte[c]=getSession("totalByte"+c);
        if(totalByte[c]!=0&&totalByte[c]!=false)...{
            window.clearInterval(halder[c]);
            var t=Math.ceil(Math.log(totalByte[c]));
            halder[c]=window.setInterval("getUploadedByte("+c+");",t*t);
        }
    }

    function getUploadedByte(c)...{
        uploadedByte[c]=getSession("uploadedByte"+c);
        var percent=Math.floor((uploadedByte[c]/totalByte[c])*100);
        //totalBar[c].innerHTML=percent+"% 共"+Math.floor(totalByte[c]/(1024*1024))+"M";
        goBar[c].style.width=percent+"%";
        if(totalByte[c]==uploadedByte[c])...{
            window.clearInterval(halder[c]);
        }
    }

    function windowOnload()...{
        uploadForms=[document.forms["uploadForm0"],document.forms["uploadForm1"]];
        //totalBar=[$("totalCountainer0"),$("totalCountainer1")];
        goBar=[$("uploadedCountainer0"),$("uploadedCountainer1")];
    }
    function windowInit()...{
        $("upload").οnclick=upload;
    }
    </script>

    </head>
    <body οnlοad="windowInit();windowOnload();">
        <iframe οnlοad="upload()" src="about:blank" name="fileUploadFrame" style="display:none;" >
        </iframe>
        <form name="uploadForm0" action=.upload method="post" enctype="multipart/form-data" target="fileUploadFrame">
            <table>
                <tr>
                    <td>
                        文件1
                    </td>
                    <td>
                        <input type="hidden" name="curCount"/>
                        <input type="hidden" name="savePath" value="images/" />
                        <input type="hidden" name="saveName" />
                        <input type="hidden" name="canOverWrite" value="true" />
                        <input type="file" name="fileData" />
                    </td>
                </tr>
            </table>
        </form>
        <div id="totalCountainer0" style="width:500px;border-style:solid;border-color:#4062E8">
            <div id="uploadedCountainer0" style="background-image:url(/1m3f/images/downloadbar.png);width:0%;"></div>
        </div>
       
       
        <form name="uploadForm1" action=.upload method="post" enctype="multipart/form-data" target="fileUploadFrame">
            <table>
                <tr>
                    <td>
                        文件2
                    </td>
                    <td>
                        <input type="hidden" name="curCount" value="2" />
                        <input type="hidden" name="savePath" value="images/" />
                        <input type="hidden" name="saveName" />
                        <input type="hidden" name="canOverWrite" value="true" />
                        <input type="file" name="fileData" />
                    </td>
                </tr>
            </table>
        </form>
        <div id="totalCountainer1" style="width:500px;border-style:solid;border-color:#4062E8">
            <div id="uploadedCountainer1" style="background-image:url(/1m3f/images/downloadbar.png);width:0%;"></div>
        </div>
        <input id="upload" type="button" value="上传" />
    </body>
    </html>

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

    package test;

    import java.io.IOException;
    import java.io.PrintWriter;

    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;

    import tools.FileUpload;

    import common.Global;

    public class UploadAction extends HttpServlet ...{

        private static final String ROOT_PATH = Global.getRootPath();
        private static final String ENCODING = Global.getEncoding();
        static final long MAX_SIZE = Global.getMaxSize();

        public void doPost(HttpServletRequest request, HttpServletResponse response) ...{

            PrintWriter out = null;
            try ...{
                // 设置字符集编码
                response.setContentType("text/html;charset=" + ENCODING);
                request.setCharacterEncoding(ENCODING);
                out = response.getWriter();
                FileUpload f = new FileUpload(request);
                f.setMaxSize(MAX_SIZE);
                f.setRootPath(ROOT_PATH);
                long start = System.currentTimeMillis();
                boolean bf = f.uploade();
                long end = System.currentTimeMillis();
                System.out.println("用时:" + (end - start));
                if (bf) ...{
                    out.print(Global.OK + Global.BLC_X_CODE);
                    out.print(f.getUserInfo());
                    out.print(Global.BLC_X_CODE);
                    out.print(f.getSysInfo());
                } else ...{
                    out.print(Global.NO_OK + Global.BLC_X_CODE);
                    out.print(f.getUserInfo());
                    out.print(Global.BLC_X_CODE);
                    out.print(f.getSysInfo());
                }
            } catch (IOException e) ...{
                e.printStackTrace();
            }
        }
    }

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


    展开全文
  • js+java进度条的文件上传,同步+异步

    千次阅读 热门讨论 2008-04-19 20:13:00
    同步上传:多个文件上传时,按顺序依次上传,后面的必须等待...同步上传2 异步上传:多个文件同时开始上传 图三.异步上传 同步上传前台代码: DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 

    同步上传:多个文件上传时,按顺序依次上传,后面的必须等待前面的上传完毕才能开始


    图一所示,正在上传第一个文件 
     
    图一.同步上传1

    图二所示,正在上传第二个文件 
     
    图二.同步上传2


    异步上传:多个文件同时开始上传

     
    图三.异步上传

    同步上传前台代码:  

    <! DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd" >
    < html  xmlns ="http://www.w3.org/1999/xhtml" >
    < head >
    < meta  http-equiv ="Content-Type"  content ="text/html; charset=UTF-8"   />
    < title > 一亩三分-上传 </ title >
    < SCRIPT  src ="/1m3f/Common_Development/Global.js" ></ SCRIPT >
    < SCRIPT  src ="/1m3f/Common_Development/HttpSubmit.js" ></ SCRIPT >
    < SCRIPT  src ="/1m3f/Common_Development/Tools.js" ></ SCRIPT >
    < script  language ="javascript" >
        
    var totalByte=[0,0];
    var uploadedByte=[0,0];
    var halder=[];
    var uploadForms=[];
    //var totalBar=[];
    var goBar=[];
    var rightfulExts={};
    rightfulExts.rar
    ="";
    rightfulExts.jpg
    ="";
    rightfulExts.exe
    ="";
    rightfulExts.iso
    ="";
    rightfulExts.gif
    ="";
    rightfulExts.ini
    ="";
    rightfulExts.rmvb
    ="";
    rightfulExts.pdf
    ="";
    var formCount=-2;

    function upload(){
        formCount
    ++;
        
    if(formCount<0||formCount>1){
            
    return false;
        }

        
        
    var ext=uploadForms[formCount].fileData.value.split(".").pop().toLowerCase();
        
    if(!(ext in rightfulExts)&&ext!=""){
            alert(
    ""+(formCount+1)+"个文件类型不匹配!");
            
    return false;
        }

        
    if(ext!=""){
            uploadForms[formCount].saveName.value
    =getNewId("13","fileUpload13")+"."+ext;
        }

        
        uploadForms[formCount].curCount.value
    =formCount;
        uploadForms[formCount].submit();
        
        totalByte[formCount]
    =0;
        halder[formCount]
    =window.setInterval("getTotalByte("+formCount+");",1);
    }


    function getTotalByte(c){
        totalByte[c]
    =getSession("totalByte"+c);
        
    if(totalByte[c]!=0&&totalByte[c]!=false){
            window.clearInterval(halder[c]);
            
    var t=Math.ceil(Math.log(totalByte[c]));
            halder[c]
    =window.setInterval("getUploadedByte("+c+");",t*t);
        }

    }


    function getUploadedByte(c){
        uploadedByte[c]
    =getSession("uploadedByte"+c);
        
    var percent=Math.floor((uploadedByte[c]/totalByte[c])*100);
        
    //totalBar[c].innerHTML=percent+"% 共"+Math.floor(totalByte[c]/(1024*1024))+"M";
        goBar[c].style.width=percent+"%";
        
    if(totalByte[c]==uploadedByte[c]){
            window.clearInterval(halder[c]);
        }

    }


    function windowOnload(){
        uploadForms
    =[document.forms["uploadForm0"],document.forms["uploadForm1"]];
        
    //totalBar=[$("totalCountainer0"),$("totalCountainer1")];
        goBar=[$("uploadedCountainer0"),$("uploadedCountainer1")];
    }

    function windowInit(){
        $(
    "upload").onclick=upload;
    }

    </ script >

    </ head >
    < body  onload ="windowInit();windowOnload();" >
        
    < iframe  onload ="upload()"  src ="about:blank"  name ="fileUploadFrame"  style ="display:none;"   >
        
    </ iframe >
        
    < form  name ="uploadForm0"  action =.upload  method ="post"  enctype ="multipart/form-data"  target ="fileUploadFrame" >
            
    < table >
                
    < tr >
                    
    < td >
                        文件1
                    
    </ td >
                    
    < td >
                        
    < input  type ="hidden"  name ="curCount" />
                        
    < input  type ="hidden"  name ="savePath"  value ="images/"   />
                        
    < input  type ="hidden"  name ="saveName"   />
                        
    < input  type ="hidden"  name ="canOverWrite"  value ="true"   />
                        
    < input  type ="file"  name ="fileData"   />
                    
    </ td >
                
    </ tr >
            
    </ table >
        
    </ form >
        
    < div  id ="totalCountainer0"  style ="width:500px;border-style:solid;border-color:#4062E8" >
            
    < div  id ="uploadedCountainer0"  style ="background-image:url(/1m3f/images/downloadbar.png);width:0%;" ></ div >
        
    </ div >
        
        
        
    < form  name ="uploadForm1"  action =.upload  method ="post"  enctype ="multipart/form-data"  target ="fileUploadFrame" >
            
    < table >
                
    < tr >
                    
    < td >
                        文件2
                    
    </ td >
                    
    < td >
                        
    < input  type ="hidden"  name ="curCount"  value ="2"   />
                        
    < input  type ="hidden"  name ="savePath"  value ="images/"   />
                        
    < input  type ="hidden"  name ="saveName"   />
                        
    < input  type ="hidden"  name ="canOverWrite"  value ="true"   />
                        
    < input  type ="file"  name ="fileData"   />
                    
    </ td >
                
    </ tr >
            
    </ table >
        
    </ form >
        
    < div  id ="totalCountainer1"  style ="width:500px;border-style:solid;border-color:#4062E8" >
            
    < div  id ="uploadedCountainer1"  style ="background-image:url(/1m3f/images/downloadbar.png);width:0%;" ></ div >
        
    </ div >
        
    < input  id ="upload"  type ="button"  value ="上传"   />
    </ body >
    </ html >

     

    异步上传前台代码:

    <! DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd" >
    < html  xmlns ="http://www.w3.org/1999/xhtml" >
    < head >
    < meta  http-equiv ="Content-Type"  content ="text/html; charset=UTF-8"   />
    < title > 一亩三分-上传 </ title >
    < SCRIPT  src ="/1m3f/Common_Development/Global.js" ></ SCRIPT >
    < SCRIPT  src ="/1m3f/Common_Development/HttpSubmit.js" ></ SCRIPT >
    < SCRIPT  src ="/1m3f/Common_Development/Tools.js" ></ SCRIPT >
    < script  language ="javascript" >
        
    var totalByte=[0,0];
    var uploadedByte=[0,0];
    var halder=[];
    var uploadForms=[];
    //var totalBar=[];
    var goBar=[];
    var rightfulExts={};
    rightfulExts.rar
    ="";
    rightfulExts.jpg
    ="";
    rightfulExts.exe
    ="";
    rightfulExts.iso
    ="";
    rightfulExts.gif
    ="";
    rightfulExts.ini
    ="";
    rightfulExts.rmvb
    ="";
    rightfulExts.pdf
    ="";

    function upload(){
        
    var l=uploadForms.length;
        
    for(var i=0;i<l;i++){
            
    var ext=uploadForms[i].fileData.value.split(".").pop().toLowerCase();
            
    if(!(ext in rightfulExts)&&ext!=""){
                alert(
    ""+(i+1)+"个文件类型不匹配!");
                
    return false;
            }

            
    if(ext!=""){
                uploadForms[i].saveName.value
    =getNewId("13","fileUpload13")+"."+ext;
            uploadForms[i].curCount.value
    =i;
            }

        }

        
        uploadForms[
    0].submit();
        totalByte[
    0]=0;
        halder[
    0]=window.setInterval("getTotalByte("+0+");",1);
        
        uploadForms[
    1].submit();
        totalByte[
    1]=0;
        halder[
    1]=window.setInterval("getTotalByte("+1+");",1);
    }


    function getTotalByte(c){
        totalByte[c]
    =getSession("totalByte"+c);
        
    if(totalByte[c]!=0&&totalByte[c]!=false){
            
    //totalBar[c].innerHTML=totalByte[c];
            window.clearInterval(halder[c]);
            
    var t=Math.ceil(Math.log(totalByte[c]));
            halder[c]
    =window.setInterval("getUploadedByte("+c+");",t*t);
        }

    }


    function getUploadedByte(c){
        uploadedByte[c]
    =getSession("uploadedByte"+c);
        
    var percent=Math.floor((uploadedByte[c]/totalByte[c])*100);
        goBar[c].style.width
    =percent+"%";
        
    if(totalByte[c]==uploadedByte[c]){
            window.clearInterval(halder[c]);
        }

    }


    function windowOnload(){
        uploadForms
    =[document.forms["uploadForm0"],document.forms["uploadForm1"]];
        
    //totalBar=[$("totalCountainer0"),$("totalCountainer1")];
        goBar=[$("uploadedCountainer0"),$("uploadedCountainer1")];
    }

    function windowInit(){
        $(
    "upload").onclick=upload;
    }

    </ script >

    </ head >
    < body  onload ="windowInit();windowOnload();" >
        
    < iframe  src ="about:blank"  name ="fileUploadFrame0"  style ="display:none;"   >
        
    </ iframe >
        
    < form  name ="uploadForm0"  action =.upload  method ="post"  enctype ="multipart/form-data"  target ="fileUploadFrame0" >
            
    < table >
                
    < tr >
                    
    < td >
                        文件1
                    
    </ td >
                    
    < td >
                        
    < input  type ="hidden"  name ="curCount" />
                        
    < input  type ="hidden"  name ="savePath"  value ="images"   />
                        
    < input  type ="hidden"  name ="saveName"   />
                        
    < input  type ="hidden"  name ="canOverWrite"  value ="true"   />
                        
    < input  type ="file"  name ="fileData"   />
                    
    </ td >
                
    </ tr >
            
    </ table >
        
    </ form >
        
    < div  id ="totalCountainer0"  style ="width:500px;border-style:solid;border-color:#4062E8" >
            
    < div  id ="uploadedCountainer0"  style ="background-image:url(/1m3f/images/downloadbar.png);width:0%;" ></ div >
        
    </ div >
        
        
        
    < iframe  src ="about:blank"  name ="fileUploadFrame1"  style ="display:none;"   >
        
    </ iframe >
        
    < form  name ="uploadForm1"  action =.upload  method ="post"  enctype ="multipart/form-data"  target ="fileUploadFrame1" >
            
    < table >
                
    < tr >
                    
    < td >
                        文件2
                    
    </ td >
                    
    < td >
                        
    < input  type ="hidden"  name ="curCount"   />
                        
    < input  type ="hidden"  name ="savePath"  value ="images"   />
                        
    < input  type ="hidden"  name ="saveName"   />
                        
    < input  type ="hidden"  name ="canOverWrite"  value ="true"   />
                        
    < input  type ="file"  name ="fileData"   />
                    
    </ td >
                
    </ tr >
            
    </ table >
        
    </ form >
        
    < div  id ="totalCountainer1"  style ="width:500px;border-style:solid;border-color:#4062E8" >
            
    < div  id ="uploadedCountainer1"  style ="background-image:url(/1m3f/images/downloadbar.png);width:0%;" ></ div >
        
    </ div >
        
    < input  id ="upload"  type ="button"  value ="上传"   />
    </ body >
    </ html >

     

    上传后台servlet代码:

    package  test;

    import  java.io.IOException;
    import  java.io.PrintWriter;

    import  javax.servlet.http.HttpServlet;
    import  javax.servlet.http.HttpServletRequest;
    import  javax.servlet.http.HttpServletResponse;

    import  tools.FileUpload;

    import  common.Global;

    public   class  UploadAction  extends  HttpServlet  {

        
    private static final String ROOT_PATH = Global.getRootPath();
        
    private static final String ENCODING = Global.getEncoding();
        
    static final long MAX_SIZE = Global.getMaxSize();

        
    public void doPost(HttpServletRequest request, HttpServletResponse response) {

            PrintWriter out 
    = null;
            
    try {
                
    // 设置字符集编码
                response.setContentType("text/html;charset=" + ENCODING);
                request.setCharacterEncoding(ENCODING);
                out 
    = response.getWriter();
                FileUpload f 
    = new FileUpload(request);
                f.setMaxSize(MAX_SIZE);
                f.setRootPath(ROOT_PATH);
                
    long start = System.currentTimeMillis();
                
    boolean bf = f.uploade();
                
    long end = System.currentTimeMillis();
                System.out.println(
    "用时:" + (end - start));
                
    if (bf) {
                    out.print(Global.OK 
    + Global.BLC_X_CODE);
                    out.print(f.getUserInfo());
                    out.print(Global.BLC_X_CODE);
                    out.print(f.getSysInfo());
                }
     else {
                    out.print(Global.NO_OK 
    + Global.BLC_X_CODE);
                    out.print(f.getUserInfo());
                    out.print(Global.BLC_X_CODE);
                    out.print(f.getSysInfo());
                }

            }
     catch (IOException e) {
                e.printStackTrace();
            }

        }

    }

     

    上传后台service代码:

    package  tools;

    import  java.io.File;
    import  java.io.FileOutputStream;
    import  java.io.IOException;
    import  java.io.RandomAccessFile;

    import  javax.servlet.ServletInputStream;
    import  javax.servlet.http.HttpServletRequest;
    import  javax.servlet.http.HttpSession;

    public   class  FileUpload  {

        
    private String userInfo = "";
        
    private String sysInfo = "";

        
    private HttpServletRequest request;
        
    private long maxSize = 1024 * 1024 * 20;
        
    private String rootPath = "";

        
    private long uploadedByte = 0;

        
    private HttpSession session = null;

        
    public FileUpload(HttpServletRequest request) {
            
    this.request = request;
    //得到session为了下面把进度信息写入session,进度条实际上就是不停的获得此信息而生成的 
    //至于怎么不停的获得后台session里的进度信息,自己看着办吧,由于太多代码的关联就不贴出来了
            session = request.getSession(false);
        }


        
    public void setRequest(HttpServletRequest request) {
            
    this.request = request;
        }


        
    public HttpServletRequest getRequest() {
            
    return this.request;
        }


        
    public void setMaxSize(long maxSize) {
            
    this.maxSize = maxSize;
        }


        
    public long getMaxSize() {
            
    return this.maxSize;
        }


        
    public void setRootPath(String rootPath) {
            
    this.rootPath = rootPath;
        }


        
    public String getRootPath() {
            
    return this.rootPath;
        }


        
    public String getUserInfo() {
            
    return userInfo;
        }


        
    public void setUserInfo(String userInfo) {
            
    this.userInfo = userInfo;
        }


        
    public String getSysInfo() {
            
    return sysInfo;
        }


        
    private String getParam(String line, String name) {
            String r 
    = "";
            
    if (line == null{
                
    return "";
            }

            
    int i = line.indexOf(name);
            
    if (i != -1{
                i 
    = i + name.length() + 2;
            }
     else {
                
    return "";
            }


            
    int j = line.indexOf('"', i);
            
    if (j != -1{
                r 
    = line.substring(i, j);
            }

            
    return r;
        }


        
    public boolean uploade() {
            
    if(session==null){
                
    this.userInfo = "您还没有登陆或登录已超时,请重新登陆";
                
    return false;
            }

            
            
    boolean bl = true;
            
    int len = 0;
            
    byte[] byteLine = new byte[1024 * 1024];
            String line 
    = null;
            ServletInputStream in 
    = null;

            RandomAccessFile fRandom 
    = null;
            FileOutputStream fStream 
    = null;

            String totalAttrib 
    = "";
            String uploadedAttrib 
    = "";
            String savePath 
    = rootPath;
            String saveName 
    = "";
            String canOverWrite 
    = "false";
            String fileName 
    = "";

            String contentType 
    = request.getContentType();
            String boundary 
    = null;
            
    // String end = null;

            boundary 
    = "--"
                    
    + contentType.substring(contentType.indexOf("boundary"+ 9);
            
    // end = boundary+"--";

            userInfo 
    = "";
            
    try {
                
    int l = byteLine.length;
                in 
    = request.getInputStream();
                
    while ((len = in.readLine(byteLine, 0, l)) != -1{
                    
    this.uploadedByte += len;
                    line 
    = new String(byteLine, 0, len);
                    
    if (line.startsWith("Content-Disposition: form-data")) {
                        String name 
    = this.getParam(line, "name");
                        len 
    = in.readLine(byteLine, 0, l);
                        
    this.uploadedByte += len;
                        len 
    = in.readLine(byteLine, 0, l);
                        
    this.uploadedByte += len;
                        String value 
    = new String(byteLine, 0, len);
                        value 
    = value.substring(0, value.length() - 2);

                        
    if("curCount".equals(name)){
                            totalAttrib 
    = "totalByte"+value;
                            uploadedAttrib 
    = "uploadedByte"+value;
                            session.setAttribute(totalAttrib, request.getContentLength());
                        }
     else if ("savePath".equals(name)) {
                            savePath 
    = rootPath + value;
                        }
     else if ("saveName".equals(name)) {
                            saveName 
    = value;
                        }
     else if ("canOverWrite".equals(name)) {
                            canOverWrite 
    = "".equals(value) ? "false" : value;
                        }
     else if ("fileData".equals(name)) {
                            fileName 
    = this.getParam(line, "filename");
                            
    if ("".equals(fileName)) {
                                
    continue;
                            }


                            File f 
    = new File(savePath);
                            
    if (!f.exists()) {
                                f.mkdirs();
                            }


                            f 
    = new File(savePath + saveName);
                            
    if (f.exists()) {
                                
    if (!"true".equals(canOverWrite)) {
                                    userInfo 
    += "文件" + fileName + "已存在;";
                                    bl 
    = false;
                                    
    continue;
                                }
     else {
                                    f.delete();
                                }

                            }


                            fStream 
    = new FileOutputStream(f);
                            len 
    = in.readLine(byteLine, 0, l);
                            line 
    = new String(byteLine, 0, len);
                            
    this.uploadedByte += len;
                            
    while (!line.startsWith(boundary)) {
                                fStream.write(byteLine, 
    0, len);
                                len 
    = in.readLine(byteLine, 0, l);
                                line 
    = new String(byteLine, 0, len);
                                
    this.uploadedByte += len;
                                session.setAttribute(uploadedAttrib, uploadedByte);
                            }

                            fRandom 
    = new RandomAccessFile(f, "rw");
                            
    long flen = fRandom.length();
                            
    if (flen > 1{
                                fRandom.setLength(flen 
    - 2);
                            }

                            fStream.flush();
                            fStream.close();
                            fRandom.close();
                        }

                    }

                }

            }
     catch (IOException e) {
                userInfo 
    += fileName + "上传失败;";
                sysInfo 
    = e.getLocalizedMessage();
                e.printStackTrace();
                bl 
    = false;
            }
    finally{
                session.setAttribute(uploadedAttrib, uploadedByte);
                session.setAttribute(totalAttrib, 
    0);
                
    try {
                    
    if (fRandom != null{
                        fRandom.close();
                    }

                    
    if(fStream!=null){
                        fStream.flush();
                        fStream.close();
                    }

                }
     catch (IOException e) {
                    sysInfo 
    = e.getLocalizedMessage();
                    bl 
    = false;
                    e.printStackTrace();
                }

            }

            
    return bl;
        }

    }

    展开全文
  • ajax进度条 异步下载进度条

    千次阅读 2012-06-26 16:39:42
    原地址:http://www.sudu.cn/info/index.php?op=article&id=254043 ... 异步下载 服务器返回excel文件的http地址 然后window.open(); 或者 download.s

    原地址:http://www.sudu.cn/info/index.php?op=article&id=254043

    http://topic.csdn.net/u/20080827/11/ad13f57d-2f1c-4c01-9b96-3bb8e8c2e9ab.html

    异步下载

    服务器返回excel文件的http地址
    然后window.open();
    或者
    <iframe id="download"></iframe>
    download.src = excel文件的http地址;

     

     

    在最近的一个项目中,有一个上传功能:上传一个cvs文件,然后解析此文件并写入数据库
    由于经常需要传很大的文件,客户完成此功能往往需要40分钟,在这个过程中,页面也没有任何提示,用户体验非常不好?
    为何不用ajax作一个进度条呢?
    分两步完成此需求:
    一:写一个简单的ajax,实现最简单的进度条功能。
    二:把此进度条改造为项目可用的进度条。

    一:最简单的进度条
    1。客户端每2秒发送一个createXMLHttpRequest请求给服务端.并得到服务端返回的进度数据.根据服务端返回的数据,用javascript更新一个table的width,
    这样就模拟了一个进度条.
    progressBar.html.内容如下:

    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

    <html>
      <head>
        <title>Ajax Progress Bar</title>
        <script type="text/javascript">
            var xmlHttp;
            var key;
            function createXMLHttpRequest() {
                if (window.ActiveXObject) {
                    xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
                } 
                else if (window.XMLHttpRequest) {
                    xmlHttp = new XMLHttpRequest();                
                }
            }

            function go() {
                createXMLHttpRequest();
                clearBar();
                var url = "ProgressBarServlet?task=create";
                var button = document.getElementById("go");
                button.disabled = true;
                xmlHttp.open("GET", url, true);
                xmlHttp.onreadystatechange = goCallback;
                xmlHttp.send(null);
            }

            function goCallback() {
                if (xmlHttp.readyState == 4) {
                    if (xmlHttp.status == 200) {
                        setTimeout("pollServer()", 2000);
                    }
                }
            }
            
            function pollServer() {
                createXMLHttpRequest();
                var url = "ProgressBarServlet?task=poll&key=" + key;
                xmlHttp.open("GET", url, true);
                xmlHttp.onreadystatechange = pollCallback;
                xmlHttp.send(null);
            }
            
            function pollCallback() {
                if (xmlHttp.readyState == 4) {
                    if (xmlHttp.status == 200) {
                        var percent_complete = xmlHttp.responseXML.getElementsByTagName("percent")[0].firstChild.data;
                        var progress = document.getElementById("progress");
                        var progressPersent = document.getElementById("progressPersent");
         progress.width = percent_complete + "%";
         progressPersent.innerHTML = percent_complete + "%";
                        if (percent_complete < 100) {
                            setTimeout("pollServer()", 2000);
                        } else {
                            document.getElementById("complete").innerHTML = "Complete!";
                            //document.getElementById("go").disabled = false;
                        }
                    }
                }
            }        
     function clearBar() {
       var progress_bar = document.getElementById("progressBar");
       var progressPersent = document.getElementById("progressPersent");
       var complete = document.getElementById("complete");
       progress_bar.style.visibility = "visible"
       progressPersent.innerHTML = "&nbsp;";
       complete.innerHTML = "Begin to upload this file...";
     }
        </script>
      </head>
    <body>
    <div id="progressBar" style="padding:0px;border:solid black 0px;visibility:hidden">
    <table width="300" border="0" cellspacing="0" cellpadding="0"  align="center">
      <tr>
        <td align="center" id="progressPersent">86%</td>
      </tr>
      <tr >
        <td>
     <table width="100%" border="1" cellspacing="0" cellpadding="0" bordercolor="#000000">
      <tr>
        <td>
     <table width="1%" border="0" cellspacing="0" cellpadding="0" bgcolor="#FF0000" id="progress">
                  <tr>
                    <td>&nbsp;</td>
                  </tr>
                </table></td>
      </tr>
    </table>
    </td>
      </tr>
      <tr>
        <td align="center" id="complete">completed</td>
      </tr>
    </table>
    </div>
    <input id = "go" name="run" type="button" value="run" onClick="go();">

    </body>
    </html>


    2:一个模拟servlet:ProgressBarServlet1。java,内容如下:


    package com.cyberobject.lcl.ajax;

    import java.io.*;

    import javax.servlet.*;
    import javax.servlet.http.*;

    /**
     *
     * @author nate
     * @version
     */
    public class ProgressBarServlet extends HttpServlet {
     private int counter = 1;
        
     /** Handles the HTTP <code>GET</code> method.
      * @param request servlet request
      * @param response servlet response
      */
     protected void doGet(HttpServletRequest request, HttpServletResponse response)
     throws ServletException, IOException {
      String task = request.getParameter("task");
      String res = "";
            
      if (task.equals("create")) {
       res = "<key>1</key>";
       counter = 1;
      }
      else {
       String percent = "";
       switch (counter) {
        case 1: percent = "10"; break;
        case 2: percent = "23"; break;
        case 3: percent = "35"; break;
        case 4: percent = "51"; break;
        case 5: percent = "64"; break;
        case 6: percent = "73"; break;
        case 7: percent = "8Array"; break;
        case 8: percent = "100"; break;
       }
       counter++;
                    
       res = "<percent>" + percent + "</percent>";
      }
            
      PrintWriter out = response.getWriter();
      response.setContentType("text/xml");
      response.setHeader("Cache-Control", "no-cache");
      out.println("<response>");
      out.println(res);
      out.println("</response>");
      out.close();
     }
        
     /** Handles the HTTP <code>POST</code> method.
      * @param request servlet request
      * @param response servlet response
      */
     protected void doPost(HttpServletRequest request, HttpServletResponse response)
     throws ServletException, IOException {
      doGet(request, response);
     }
        
     /** Returns a short description of the servlet.
      */
     public String getServletInfo() {
      return "Short description";
     }
    }
    3:在web。xml中配置好servlet映射:
      <!-- Action Servlet Mapping -->
      <servlet>
       <servlet-name>ProgressBarServlet</servlet-name>
       <display-name>ProgressBarServlet</display-name>
       <servlet-class>com.cyberobject.lcl.ajax.ProgressBarServlet</servlet-class>
      </servlet>

        <servlet-mapping>
       <servlet-name>ProgressBarServlet</servlet-name>
       <url-pattern>/ProgressBarServlet</url-pattern>
      </servlet-mapping>


    此时进度条已经可以运行了。接下来的工作就是把它移植到我们的系统。
      二:
      1:在写数据库的class DbOperater中,增加一个progress属性
      private int progress;

      2:在写数据库的class中,增加一个getProgress()方法:
      public int getProgress()
      {
     return progress;
      }
      3: 在写库的for循环中, progress++;
      4:在调用DbOperater的servlet中调用DbOperater的getProgress()方法,这样就为进度条提供了实时数据.
      5:另外:servlet的doGet()用来获得进度数据,doPost()用来上传文件和写库操作.彼此分工明确.
      特此存档.

     

    展开全文
  • Task<Integer> task = new Task<Integer>() { @Override protected Integer call() throws Exception { // TODO Auto-generated method stub return null; } @Override protected void running...
  • java 进度条上传

    2013-02-28 10:00:04
    上传ajax方式,可用juery.ajaxupload插件 上传一个地址 url_1:读取文件大小,和上传的字节大小,放到session中 查看进度地址 url_2:从session中读取上传进度...两个请求都是ajax异步并行。 读取进度轮询请求...
    上传ajax方式,可用juery.ajaxupload插件
    

    上传一个地址 url_1:读取文件大小,和上传的字节大小,放到session中

    查看进度地址 url_2:从session中读取上传进度,页面展示。

    两个请求都是ajax异步并行。
    读取进度轮询请求
    展开全文
  • 异步加载进度条,屏蔽搜索键

    千次阅读 2011-06-16 00:48:00
    当进行耗时的操作时,就会写个进度条在界面上运行。... 异步加载进度条屏蔽返回键很简单,只要设置dialog.setCancelable(false);即可。 2. 可是屏蔽搜索键没有现成的东西。 想法一,重写onKeyDown函数:Java代码
  • java后台监控进程;jQuery发回调函数;...就是异步同时上传,同时监控。现在的问题是java后台的servlet中的方法的变量如何循环如何写。jQuery的回调函数怎么写?请高人指点。(除了jQuery库之外不加任何插件)
  • java中的进度条的显示

    万次阅读 2015-06-05 18:05:11
    最近需要用到进度条,于是就查看了一下oracle的文档,看了一下java进度条的显示方法,现在就总结一下。  java提供了三种关于进度条的显示类。  1:JProgressBar(进程条)  2:ProgressMonitor(进程监视)  3...
  • java使用ajax实现进度条java使用ajax实现进度条
  • //异步加载进程 private AsyncOperation async; void Start() { loadPanel.SetActive(false);//一开始禁用加载层。 } //点击按钮跳场景 public void NewGamePressed() { StartCoroutine(LoadScene());...
  • 本文主要演示Jquery progressbar的进度条功能。js通过ajax请求向后台实时获取当前的进度值。后台将进度值存储在cookie中,每次请求后,将进度条的值增2个。以此演示进度条的实时显示功能。前台index.jspjsp代码如下...
  • 异步上传文件,同时显示进度条。。界面的话,在fireFox 下面没有问题
  • android AsyncTask异步下载并更新进度条

    千次阅读 2013-06-18 15:55:00
    AsyncTask异步下载并更新进度条 //如果不是很明白请看上篇文章的异步下载AsyncTask 第一个参数:String 传入的是需要下载的地址 第二个参数:Integer 是进度条的进度 第三个参数:String 下载后的结果,如果您...
  • java 异步执行任务,返回进度

    万次阅读 2012-04-01 23:33:17
    import java.util.ArrayList; import java.util.List; import java.util.concurrent.Callable; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent
  • Java上传文件进度条的实现方法(附demo源码下载)本文实例讲述了Java上传文件进度条的实现方法。分享给大家供大家参考,具体如下:东西很简单,主要用到commons-fileupload,其中有一个progressListener的接口,该接口...
  • 异步任务 AsyncTask 进度条的更新

    千次阅读 2015-10-11 11:12:07
    进度条的更新问题 创建工程 activity_main.xml 布局文件代码 android:layout_width="match_parent" android:layout_height="match_parent"
  • java web 文件异步上传(显示进度条) ** 前端页面 html <script language="javascript" src="jquery-3.4.1.js"></script> <!-- 弹框插件 --> <script language="javascript" src="toastr....
  • Android 异步AsyncTask下载 含有进度条

    千次阅读 2013-12-11 17:48:21
    在Android中实现异步任务机制有两种方式,Handler和AsyncTask。 Handler模式需要为每一个任务创建一个新的线程,任务完成后通过Handler实例向UI线程发送消息,完成界面的更新,这种方式对于整个过程的控制比较精细...
  • 为什么要用异步任务? 在android中只有在主线程才能对ui进行更新操作,而其它线程不能直接对ui进行操作 android本身是一个多线程的操作系统,我们不能把所有的操作都放在主线程中操作 ,比如一些耗时操作。如果...
  • @Override protected ModelAndView onSubmit(HttpServletRequest request, HttpServletResponse response, Object command, BindException errors) throws Exception { FileUploadForm form = (FileUploadFo...
  • 文章目录AsyncTask的定义作用优点常用方法和方法的执行顺序进度条例子布局MyAsyncTack类MainActivity类效果 AsyncTask的定义 1、一个Android 已封装好的轻量级异步类 2、 属于抽象类,即使用时需 实现子类 作用 1、...
  • AsyncTask 异步加载网络图片 并使用进度条显示进度 这里我还使用了Thread方式进行加载 作为比较
  • java执行程序有进度条

    2014-11-19 10:51:20
    swing在执行的任务的时候,如何显示任务的进度条,我们来看看swing是如何实现的。 // 开始生成 public JProgressBar progressBar;//xml文件转换进度条 public JProgressBar ...()//这个方法可以执行异步的...
  • 异步类下载 带进度条

    2011-12-23 09:23:05
    package ... import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import org.apache.http.HttpEntity; import org.a...
  • 异步下载文件的代码如下 import android.app.Activity; import android.os.Bundle; import android.os.Environment; import android.os.Handler; import android.os.Message; import android.view.View; import ...

空空如也

空空如也

1 2 3 4 5 ... 20
收藏数 12,210
精华内容 4,884
关键字:

java异步进度条

java 订阅