servlet+jquery实现文件上传进度条示例代码

前端之家收集整理的这篇文章主要介绍了servlet+jquery实现文件上传进度条示例代码前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

现在文件上传,特别是大文件上传,都需要进度条,让客户知道上传进度。

本文简单记录下如何弄进度条,以及一些上传信息,比如文件的大小,上传速度,预计剩余时间等一些相关信息。代码是匆忙下简单写的,一些验证没做,或代码存在一些隐患,不严谨的地方。本文代码只供参考。

进度条的样式多种多样,有些网站弄得非常绚烂漂亮。本文UI端不太懂,只会一些简单的基本的css而已,所以进度条弄得不好看。本文侧重的给读者提供一个参考,一个实现思路而已。

注:由于jQuery版本用的是2.1.1,所以如果跑本例子源码,请用IE9以上或火狐、谷歌浏览器测试。

接收文件上传的servlet

UploadFileServlet.Java

import java.io.IOException;
import java.util.Date;
import java.util.Map;

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

import com.fei.util.FileUploadUtil;

public class UploadFileServlet extends HttpServlet {

private static final long serialVersionUID = 1L;

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

public void doPost(HttpServletRequest request,IOException {
try {
long start = System.currentTimeMillis();
System.out.println("开始上传文件........." );
Map<String,String> params = FileUploadUtil.upload(request);
System.out.println("文件上传完成........." );
System.out.println("文件上次用时:"+(System.currentTimeMillis()-start)+"毫秒");
} catch (Exception e) {
e.printStackTrace();
}
}
}

上传文件进行下载到服务器的处理

FileUploadUtil.java

import java.io.File;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

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;

public class FileUploadUtil {

/**

  • 文件上传保存路径
    */
    private static final String SAVE_FILEPATH = "/fileupload/";
    /**
  • 文件上传临时保存路径
    */
    private static final String SAVE_FILE_TMPPATH = "/fileupload/tmp/";
    /**
  • 上传文件的最大值M
    /
    private static final int MAX_FILE_SIZE = 100
    1024*1024;
    /**
  • 文件数据在内存中超过多少M后,就写入临时文件
    /
    private static final int THRESHOLD_SIZE = 2
    1024*1024;

private static final String ENCODING = "UTF-8";

/**

  • 处理文件上传的表单
  • 下载文件,并返回文件名称及普通表单域中其它属性
  • 获取文件
    */
    public static Map<String,String> upload(HttpServletRequest request)throws Exception{
    Map<String,String> params = new HashMap<String,String>();
String savePath = request.getSession().getServletContext() 
    .getRealPath(SAVE_FILEPATH)+ File.separator; 
String savePathTemp = request.getSession().getServletContext() 
    .getRealPath(SAVE_FILE_TMPPATH)+ File.separator; 

File saveFileTempDir = new File(savePathTemp); 

DiskFileItemFactory factory = new DiskFileItemFactory(); 
//当内存中<a href="https://www.jb51.cc/tag/wenjian/" target="_blank" class="keywords">文件</a>数据达到THRESHOLD_SIZE后,就写入临时<a href="https://www.jb51.cc/tag/wenjian/" target="_blank" class="keywords">文件</a>中,避免<a href="https://www.jb51.cc/tag/shangchuan/" target="_blank" class="keywords">上传</a>大<a href="https://www.jb51.cc/tag/wenjian/" target="_blank" class="keywords">文件</a>时,消化太多内存 
factory.setSizeThreshold(THRESHOLD_SIZE); 
factory.setRepository(saveFileTempDir); 

ServletFileUpload upload = new ServletFileUpload(factory); 
upload.setHeaderEncoding(ENCODING); 
upload.setSizeMax(MAX_FILE_SIZE); 

FileUploadInfo fileUploadInfo = new FileUploadInfo(); 
upload.setProgressListener(new FileUploadListener(fileUploadInfo)); 
request.getSession().setAttribute("uploadInfo",fileUploadInfo); 

List items = upload.parseRequest(request); 
Iterator iter = items.iterator(); 
int fileNum = 1; 
while(iter.hasNext()){ 
  FileItem item = (FileItem) iter.next(); 
  if (item.isFormField()) {//普通表单域 
    params.put(item.getFieldName(),item.getString()); 
  } else { 
    String fileName = item.getName().replace("/","\\"); 
    int i = fileName.lastIndexOf("\\"); 
    fileName = fileName.substring(i+1); 
    //避免重复 
    fileName = System.currentTimeMillis() + fileName; 

    File uploadedFile = new File(savePath + fileName); 
    item.write(uploadedFile); 

    params.put("fileName0"+fileNum,fileName); 
    fileNum ++; 

  } 
} 


return params; 

}

}

class FileUploadListener implements ProgressListener{

FileUploadInfo fileUploadInfo = null;

public FileUploadListener(FileUploadInfo fileUploadInfo) {
this.fileUploadInfo = fileUploadInfo;
}

@Override
public void update(long uploadSize,long totalSize,int itemNum) {
this.fileUploadInfo.setTotalSize(totalSize);
this.fileUploadInfo.setUploadSize(uploadSize);

}

}

上传文件的一些信息

FileUploadInfo.java

public class FileUploadInfo {

private final int K = 1024;

private final int M = K * 1024;

/**

  • 总大小
    */
    private long totalSize;
    /**
  • 开始上传时间
    */
    private long startTime = System.currentTimeMillis();
    /**
  • 上传多少
    */
    private long uploadSize;

/**

  • 上传速度(K/S)
    /
    public double getUploadSpeed_K(){
    long currentTime = System.currentTimeMillis();
    long usedTime = currentTime - startTime;
    if(usedTime == 0.0){
    return 0.0;
    }
    return getUploadSize_K()/usedTime
    1000d;
    }
    /**
  • 获取上传百分比
  • @return
    /
    public double getUploadPercent(){
    return (getUploadSize()
    1.00/getTotalSize())*100d;
    }
    /**
  • 剩余时间(s)
  • @return
    */
    public double getRemainTime(){
    double speedKB = getUploadSpeed_K();
    if(speedKB<= 0.00){
    return -1d;
    }
    return (getTotalSize_K() - getUploadSize_K())/speedKB;
    }
    /**
  • 上传时间
  • @return
    */
    public double getUseTime(){
    return (System.currentTimeMillis() - startTime)/1000d;
    }

public long getTotalSize() {
return totalSize;
}

public double getTotalSize_K(){
return getTotalSize()*1.0/K;
}

public double getTotalSize_M(){
return getTotalSize()*1.0/M;
}

public long getUploadSize() {
return uploadSize;
}

public double getUploadSize_K(){
return getUploadSize()/K;
}

public double getUploadSize_M(){
return getUploadSize()/M;
}

public void setTotalSize(long totalSize) {
this.totalSize = totalSize;
}

public void setUploadSize(long uploadSize) {
this.uploadSize = uploadSize;
}

private String double2String(double d){
return String.format("%.2f",d);
}

public String toString(){
return "{"+
"'totalSize':'"+double2String(getTotalSize_M())+"M',"+
"'uploadSize':'"+double2String(getUploadSize_M())+"M',"+
"'uploadSpeed':'"+double2String(getUploadSpeed_K())+"KB/s',"+
"'uploadPrecent':'"+double2String(getUploadPercent())+"',"+
"'remainTime':'"+(getRemainTime()<0?"未知":double2String(getRemainTime()))+"s"+"',"+
"'useTime':'"+double2String(getUseTime())+"s' "+
"}";
}
}

读取文件上传进度的servlet

UploadFileProgressServlet.java

import java.io.IOException;

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

import com.fei.util.FileUploadInfo;

public class UploadFileProgressServlet extends HttpServlet {

private static final long serialVersionUID = 1L;

public void doGet(HttpServletRequest request,response);
}

public void doPost(HttpServletRequest request,IOException {
String responseContent = "";

Object obj = request.getSession().getAttribute("uploadInfo"); 
if(obj == null){ 
  responseContent = "{'data':'NoData'}"; 
}else{ 
  FileUploadInfo uploadInfo = (FileUploadInfo)obj; 
  responseContent = uploadInfo.toString(); 
  if(uploadInfo.getUploadPercent()== 100.0){ 
    request.getSession().setAttribute("uploadInfo",null); 
  } 
} 
System.out.println("<a href="https://www.jb51.cc/tag/wenjian/" target="_blank" class="keywords">文件</a>上次情况:"+responseContent); 
response.getWriter().print(responseContent); 

}
}

前台页面upload2.html

上传文件:
Box">