java带进度条的上传文件.docx
《java带进度条的上传文件.docx》由会员分享,可在线阅读,更多相关《java带进度条的上传文件.docx(15页珍藏版)》请在冰豆网上搜索。
java带进度条的上传文件
JSP页面:
upload.jsp
<%@pagelanguage="java"import="java.util.*"pageEncoding="UTF-8"%>
<%
Stringpath=request.getContextPath();
StringbasePath=request.getScheme()+":
//"+request.getServerName()+":
"+request.getServerPort()+path+"/";
%>
DOCTYPEHTMLPUBLIC"-//W3C//DTDHTML4.01Transitional//EN">
">
varover=false;
varinter;
functionupload(){
over=false;
$("#state").html("")
$("#progress").css("width","0")
$("input[type=submit]").attr("disabled",true);
$("#progress").css("width","0%");
$("#state").html("正在上传...总大小:
0MB,已上传:
0MB,0%,已用时:
0秒,剩余时间:
0秒,速度:
0KB/S");
inter=setInterval(req,1000);
}
functionreq(){
//如果上传已经完成
if(over){
clearInterval(inter);
return;
varurl="upload/AjaxServlet";
$.get(url,function(date){
varstate=date.split("-");
"+state[4]+"MB,已上传:
"+state[3]+"MB,"+state[2]+"%,已用时:
"+state[0]+"秒,剩余时间:
"+state[5]+"秒,速度:
"+state[1]+"KB/S");
$("#progress").animate({width:
state[2]+"%"},500);
if(state[3]==state[4]){
over=true;
$("input[type=submit]").attr("disabled",false);
$("#state").html("上传已完成,总大小:
});
#728820;height:50px;width:0">
#728820;height:
50px;width:
0">
Servlet:
AjaxServlet.java
packagecom.hongfei.servlet;
importjava.io.IOException;
importjava.io.PrintWriter;
importjavax.servlet.ServletException;
importjavax.servlet.http.HttpServlet;
importjavax.servlet.http.HttpServletRequest;
importjavax.servlet.http.HttpServletResponse;
importcom.hongfei.entity.Upload;
@SuppressWarnings("serial")
publicclassAjaxServletextendsHttpServlet{
/**
*Constructoroftheobject.
*/
publicAjaxServlet(){
super();
*Destructionoftheservlet.
publicvoiddestroy(){
super.destroy();//Justputs"destroy"stringinlog
//Putyourcodehere
*ThedoGetmethodoftheservlet.
*
*Thismethodiscalledwhenaformhasitstagvaluemethodequalstoget.
*@paramrequesttherequestsendbytheclienttotheserver
*@paramresponsetheresponsesendbytheservertotheclient
*@throwsServletExceptionifanerroroccurred
*@throwsIOExceptionifanerroroccurred
publicvoiddoGet(HttpServletRequestrequest,HttpServletResponseresponse)
throwsServletException,IOException{
response.setHeader("Cache-Control","no-store");//禁止浏览器缓存
response.setHeader("Pragrma","no-cache");//禁止浏览器缓存
response.setDateHeader("Expires",0);//禁止浏览器缓存
response.setContentType("text/html");
PrintWriterout=response.getWriter();
Uploadupload=null;
upload=(Upload)request.getSession().getAttribute("upload");
if(null==upload)
longcurrentTime=System.currentTimeMillis();
//计算已用时,以S为单位
longtime=(currentTime-upload.getStartTime())/1000+1;
//计算速度,以kb为单位
longspeed=(long)(double)upload.getUploadSize()/1024/time;
//计算百分比
intpercent=(int)((double)upload.getUploadSize()/(double)upload.getTotalSize()*100);
//已经完成
intmb=(int)upload.getUploadSize()/1024/1024;
//总共有多少
inttotalMb=(int)upload.getTotalSize()/1024/1024;
//剩余时间
intshenYu=(int)((upload.getTotalSize()-upload.getUploadSize())/1024/speed);
Stringstr=time+"-"+speed+"-"+percent+"-"+mb+"-"+totalMb+"-"+shenYu;
out.print(str);
out.flush();
out.close();
*ThedoPostmethodoftheservlet.
*Thismethodiscalledwhenaformhasitstagvaluemethodequalstopost.
publicvoiddoPost(HttpServletRequestrequest,HttpServletResponseresponse)
out
.println("
DOCTYPEHTMLPUBLIC\"-//W3C//DTDHTML4.01Transitional//EN\">");
out.println("");
out.println("
out.print("Thisis");
out.print(this.getClass());
out.println(",usingthePOSTmethod");
*Initializationoftheservlet.
*@throwsServletExceptionifanerroroccurs
publicvoidinit()throwsServletException{
Upload.java
importjava.io.File;
importjava.io.FileOutputStream;
importjava.io.InputStream;
importjava.util.Iterator;
importjava.util.List;
importmons.fileupload.FileItem;
importmons.fileupload.FileUploadException;
importmons.fileupload.disk.DiskFileItemFactory;
importmons.fileupload.servlet.ServletFileUpload;
importcom.hongfei.lister.UploadLister;
publicclassUploadextendsHttpServlet{
publicUpload(){
out.println(",usingtheGETmethod");
@SuppressWarnings({"deprecation","unchecked"})
com.hongfei.entity.Uploadupload=newcom.hongfei.entity.Upload();
UploadListerlister=newUploadLister(upload);
ServletFileUploadservletFileUpload=newServletFileUpload(newDiskFileItemFactory());
//只是上传监听器
servletFileUpload.setProgressListener(lister);
request.getSession().setAttribute("upload",upload);
Listlist=null;
try{
list=servletFileUpload.parseRequest(request);
}catch(FileUploadExceptione){
e.printStackTrace();
for(Iteratoriter=list.iterator();iter.hasNext();){
//得到文件对象
FileItemfileItem=(FileItem)iter.next();
//是表单才进行处理
if(fileItem.isFormField()){
break;
//同意linux和windows的路径分隔符
Stringname=fileItem.getName().replaceAll("/","\\");
//得到文件名
intindex=name.lastIndexOf("\\");
StringfileFileName="";
if(index==-1){
fileFileName=name;
}else{
fileFileName=name.substring(index+1);
InputStreamfileInputStream=fileItem.getInputStream();
Stringpath=request.getRealPath("/upload");
//也可不用自己写实现方法直接使用,fileItem.write(uploadFile);
FileuploadFile=newFile(path,fileFileName);
//首先要确认路径是否存在
uploadFile.getParentFile().mkdirs();
//检查文件是否已经存在
if(!
uploadFile.exists()){
//建立文件
uploadFile.createNewFile();
FileOutputStreamout2=newFileOutputStream(uploadFile);
//开始copy文件
@SuppressWarnings("unused")
intlen=0;//每次读取的字节数
byte[]bytes=newbyte[1024];
while((len=fileInputStream.read(bytes,0,bytes.length))!
=-1){
out2.write(bytes);
out2.flush();
out2.close();
fileInputStream.close();
*Initializationo
copyright@ 2008-2022 冰豆网网站版权所有
经营许可证编号:鄂ICP备2022015515号-1