您的位置:首页 > 编程语言 > Java开发

js+java 带进度条的文件上传,同步+异步

2008-04-19 20:13 309 查看
同步上传:多个文件上传时,按顺序依次上传,后面的必须等待前面的上传完毕才能开始

图一所示,正在上传第一个文件



图一.同步上传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;


}


}

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: