实现思路:
1、首先自定义一个进度坚挺实现类ProgressListener接口,重写upload方法。
2、通过以读取的字节数跟文件总的字节数生成百分比,将值放到session中
3、创建一个servlet用来获取session中的百分比
4、在上传文件界面,在表单提交时,Ajax每个100毫秒访问第三步中创建的servlet响应的百分比值,显示在界面。
参考代码:
自定义监听类实现ProgressListener
package cn.progressBar;
import java.text.NumberFormat;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import org.apache.commons.fileupload.ProgressListener;
/**
* 自定义监听类实现ProgressListener
* @author l
*
*/
//@WebListener
public class MyProgressListener implements ProgressListener{
private double megaBytes = -1;
private HttpSession session;
public MyProgressListener(){
}
public MyProgressListener(HttpServletRequest request){
session = request.getSession();
}
@Override
public void update(long pBytesRead, long pContentLength, int pItems) {
// TODO Auto-generated method stub
double mBytes = pBytesRead / (1024*1024); //pBytesRead到目前为止读取文件的比特数
double total=pContentLength/(1024*1024); //pContentLength 文件总大小
if (megaBytes == mBytes) {
return;
}
System.out.println("文件总大小:"+total+"M");
System.out.println("已读取:"+mBytes+"M");
megaBytes = mBytes;
System.out.println("目前正在读取第几个文件 " + pItems); //pItems目前正在读取第几个文件
if (pContentLength == -1) {
System.out.println("So far, " + pBytesRead + " bytes have been read.");
} else {
System.out.println("So far, " + pBytesRead + " of " + pContentLength
+ " bytes have been read.");
double read=(mBytes/total);
NumberFormat nf=NumberFormat.getPercentInstance();
System.out.println("read===>"+nf.format(read));//生成读取的百分比 并放入session中
session.setAttribute("read", nf.format(read));
}
}
}
封装FileUpload 用来接收request中的表单域 和 file文件域
package cn.progressBar;
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.FileItemFactory;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
public class FileUpload {
private Map<String,String> params;
private Map<String,FileItem> files;
public FileUpload() {
params=new HashMap<String, String>();
files=new HashMap<String, FileItem>();
}
@SuppressWarnings("rawtypes")
public void setMap(HttpServletRequest request){
// Create a factory for disk-based file items
FileItemFactory factory = new DiskFileItemFactory();
// Create a new file upload handler
ServletFileUpload upload = new ServletFileUpload(factory);
upload.setHeaderEncoding("utf-8");
upload.setProgressListener(new MyProgressListener(request));//设置进度监听器
// Parse the request
try {
List items = upload.parseRequest(request);
Iterator iter = items.iterator();
while (iter.hasNext()) {
FileItem item = (FileItem) iter.next();
if (item.isFormField()) {
String name = item.getFieldName();
String value = item.getString();
params.put(name, value);
}
else{
String name=item.getFieldName();
files.put(name, item);
}
}
} catch (FileUploadException e) {
e.printStackTrace();
}
}
public Map<String, String> getParams() {
return params;
}
public Map<String, FileItem> getFiles() {
return files;
}
//用来获取文件的名字
public String getFileName(FileItem item){
String fName=item.getName();
System.out.println("fname=====>"+fName);
int lastIndex=fName.lastIndexOf("\\");
fName=fName.substring(lastIndex+1);
System.out.println("new fname=====>"+fName);
return fName;
}
}
实现上传文件servlet
package cn.progressBar;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Map;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.fileupload.FileItem;
@WebServlet("/FileUploadServlet")
public class FileUploadServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html;charset=utf-8");
PrintWriter out = response.getWriter();
FileUpload fu=new FileUpload();
fu.setMap(request);//解析request
Map<String,FileItem> files=fu.getFiles();
String fileName =fu.getFileName(files.get("file"));
File file=new File(this.getServletContext().getRealPath("upload\\"+fileName));
try {
files.get("file").write(file);
} catch (Exception e) {
e.printStackTrace();
}
out.println("<script>alert('上传成功!');history.go(-1);</script>");
}
}
实现用来响应上传进度的servlet FileUploadStatus
package cn.progressBar;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
@WebServlet("/FileUploadStatus")
public class FileUploadStatus extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("--------------------------------------------------------------------------------------------------------------------------");
response.setContentType("text/html;charset=utf-8");
PrintWriter out = response.getWriter();
HttpSession session=request.getSession();
String status=(String) session.getAttribute("read");//获取上传进度百分比
System.out.println(status+"FileUploadStatus");
out.println(status);//响应
}
}
index.jsp 完整内容
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
<script type="text/javascript" src="js/jquery-1.11.0.js"></script>
<script type="text/javascript">
function callback() {
//alert("=======");
//alert("*********************");
$.ajax({
//http://localhost:8080/progressBar/index.jsp
type : "POST",
url : "FileUploadStatus",//响应文件上传进度的servlet FileUploadStatus
success : function(msg) {
//document.getElementById("span").innerHTML = msg;//显示读取百分比 已上传
//document.getElementById("table").width = msg;//通过表格宽度 实现进度条
var bl = parseInt(msg);
//alert(bl);
if(bl<20 && bl >=0){
$("#show").html("<div style='width:"+msg+";background-color: #f90;border-radius:8px;text-align:right'>"+msg+"</div>");
}
if(bl<40 && bl >=20){
$("#show").html("<div style='width:"+msg+";background-color: #c90;border-radius:8px;text-align:right'>"+msg+"</div>");
}
if(bl<60 && bl >=40){
$("#show").html("<div style='width:"+msg+";background-color: #990;border-radius:8px;text-align:right'>"+msg+"</div>");
}
if(bl<75 && bl >=60){
$("#show").html("<div style='width:"+msg+";background-color: #690;border-radius:8px;text-align:right'>"+msg+"</div>");
}
if(bl<90 && bl >=75){
$("#show").html("<div style='width:"+msg+";background-color: #390;border-radius:8px;text-align:right'>"+msg+"</div>");
}
if(bl<=100 && bl >=90){
$("#show").html("<div style='width:"+msg+";background-color: #090;border-radius:8px;text-align:right'>"+msg+"</div>");
}
//$("#show").html("<div style='width:"+msg+";background-color: orange;border-radius:8px;text-align:right'>"+msg+"</div>");
}
});
}
function formSubmit(){
window.setInterval("callback()", 10);//每隔100毫秒执行
document.form.submit();
}
</script>
</head>
<body>
<form action="FileUploadServlet" method="post"
enctype="multipart/form-data" target="_parent" name="form">
<input type="file" name="file" ><input type="button" οnclick="formSubmit()" value="提交">
</form>
<!-- <span id="span"></span> -->
<!-- <table width="300px;" border="0">
<tr>
<td>
<table id="table" height="30px" style="background-color: gray;">
<tr>
<td align="right"><span id="span"></span></td>
</tr>
</table>
实现进度条的显示
</td>
</tr>
</table> -->
<div style="width:300px;border-radius:8px;" id="show">
</div>
</body>
</html>
效果图:
注:不要忘了引用jquery
参考:http://blog.csdn.net/hxlzpnyist/article/details/7601611