欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

java ajax 上传 加进度条 博客分类: java JavaAjaxServletCSSjson 

程序员文章站 2024-03-04 18:20:30
...
项目中要用到上传.同时要有进度条提示 从网上找了些解决方案自己学习了下.做个总结:
上传过程中使用到的是commons-fileupload-1.2.1.jar和commons-io-1.4.jar
上传页面中有一个form表单设置enctype="multipart/form-data" 同时放置一个隐藏的iframe同时设置表单的target为iframe的名称.从而达到伪ajax提交。
进度条:我们在上传的时候监听上传流的长度  实现ProgressListener接口重写update方法该方法有三个参数第一个是已上传文件的流的长度,第二个参数是文件的长度,第三个是文件数.把数据封装起来保存到session中然后用js访问servlet从session取得数据同时设置div的宽度加上css就能够实现进度条功能 代码在下面

页面很简单:
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
   
    <title>上传进度条</title>
<script type="text/javascript" src="./js/jquery-1.3.2.min.js"></script>
<script type="text/javascript" src="./js/progressBar.js"></script>
<link type="text/css" rel="stylesheet" href="./css/progressBar.css">

  </head>
 
  <body>
  <iframe id='target_upload' name='target_upload' src=''
style='display: none'></iframe>
   <form action="./upload" id="uploadForm" enctype="multipart/form-data" method="post" target="target_upload">
   <input type="file" name="upload"> <input type="button" id="subButton" value="上传">
   </form>
   <div id="progress">
   <div id="title"><span id="text">上传进度</span><div id="close">X</div></div>
   <div id="progressBar">
   <div id="uploaded"></div>
   </div>
   <div id="info"></div>
   </div>
  </body>
</html>

--------------------------
progressBar.js


var startTime;
$(document).ready(function () {
$("#subButton").click(function () {
var myDate = new Date();
startTime = myDate.getTime();
$(this).attr("disabled", true);
$("#uploadForm").submit();
$("#progress").show();
window.setTimeout("getProgressBar()", 1000);
});
$("#close").click(function(){$("#progress").hide();});
});
function getProgressBar() {
var timestamp = (new Date()).valueOf();
var bytesReadToShow = 0;
var contentLengthToShow = 0;
var bytesReadGtMB = 0;
var contentLengthGtMB = 0;
$.getJSON("/filesystem/getBar", {"t":timestamp}, function (json) {
var bytesRead = (json.pBytesRead / 1024).toString();
if (bytesRead > 1024) {
bytesReadToShow = (bytesRead / 1024).toString();
bytesReadGtMB = 1;
}else{
bytesReadToShow = bytesRead.toString();
}
var contentLength = (json.pContentLength / 1024).toString();
if (contentLength > 1024) {
contentLengthToShow = (contentLength / 1024).toString();
contentLengthGtMB = 1;
}else{
contentLengthToShow= contentLength.toString();
}
bytesReadToShow = bytesReadToShow.substring(0, bytesReadToShow.lastIndexOf(".") + 3);
contentLengthToShow = contentLengthToShow.substring(0, contentLengthToShow.lastIndexOf(".") + 3);
if (bytesRead == contentLength) {
$("#close").show();
$("#uploaded").css("width", "300px");
if (contentLengthGtMB == 0) {
$("div#info").html("\u4e0a\u4f20\u5b8c\u6210\uff01\u603b\u5171\u5927\u5c0f" + contentLengthToShow + "KB.\u5b8c\u6210100%");
} else {
$("div#info").html("\u4e0a\u4f20\u5b8c\u6210\uff01\u603b\u5171\u5927\u5c0f" + contentLengthToShow + "MB.\u5b8c\u6210100%");
}
window.clearTimeout(interval);
$("#subButton").attr("disabled", false);
} else {
var pastTimeBySec = (new Date().getTime() - startTime) / 1000;
var sp = (bytesRead / pastTimeBySec).toString();
var speed = sp.substring(0, sp.lastIndexOf(".") + 3);
var percent = Math.floor((bytesRead / contentLength) * 100) + "%";
$("#uploaded").css("width", percent);
if (bytesReadGtMB == 0 && contentLengthGtMB == 0) {
$("div#info").html("\u4e0a\u4f20\u901f\u5ea6:" + speed + "KB/Sec,\u5df2\u7ecf\u8bfb\u53d6" + bytesReadToShow + "KB,\u603b\u5171\u5927\u5c0f" + contentLengthToShow + "KB.\u5b8c\u6210" + percent);
} else {
if (bytesReadGtMB == 0 && contentLengthGtMB == 1) {
$("div#info").html("\u4e0a\u4f20\u901f\u5ea6:" + speed + "KB/Sec,\u5df2\u7ecf\u8bfb\u53d6" + bytesReadToShow + "KB,\u603b\u5171\u5927\u5c0f" + contentLengthToShow + "MB.\u5b8c\u6210" + percent);
} else {
if (bytesReadGtMB == 1 && contentLengthGtMB == 1) {
$("div#info").html("\u4e0a\u4f20\u901f\u5ea6:" + speed + "KB/Sec,\u5df2\u7ecf\u8bfb\u53d6" + bytesReadToShow + "MB,\u603b\u5171\u5927\u5c0f" + contentLengthToShow + "MB.\u5b8c\u6210" + percent);
}
}
}
}
});
var interval = window.setTimeout("getProgressBar()", 500);
}

-----------------
css
body{font-size:14px;}
#progress{left:400px;top:200px;position:absolute;width:400px;height:120px;border:1px solid black;display:none;}
#progressBar{border:1px solid black;width:300px;height:20px;margin-left:50px;margin-top:60px;}
#uploaded{height:20px;width:1px;background-color:red;}
#title{height:20px;background-color:blue;pading:-10px;}
#close{width:10px;height:10px;right:1px;top:0px;position:absolute;display:none;cursor:pointer;}


---------------
上传处理servlet
package com.dynastarter.sc.file.utils;



import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Iterator;
import java.util.List;

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

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

public class uploadServlet extends HttpServlet {

/**
*
*/
private static final long serialVersionUID = 1L;

@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
// TODO Auto-generated method stub
this.doPost(req, resp);
}

@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
DiskFileItemFactory factory = new DiskFileItemFactory();
factory.setSizeThreshold(2048*1024);
myProgressListener getBarListener = new myProgressListener(req);
ServletFileUpload upload = new ServletFileUpload(factory);
upload.setProgressListener(getBarListener);
try {
List formList = upload.parseRequest(req);
System.out.println("============="+formList.size());
Iterator<Object> formItem = formList.iterator();
// 将进度监听器加载进去
while (formItem.hasNext()) {
FileItem item = (FileItem) formItem.next();
if (item.isFormField()) {
System.out.println("Field Name:" + item.getFieldName());
} else {
String fileName = item.getName().substring(item.getName().lastIndexOf("\\")+1);
File file = new File("e:\\"+ fileName);
System.out.println("e:\\" + fileName);
OutputStream out = item.getOutputStream();
InputStream in = item.getInputStream();
req.getSession().setAttribute("outPutStream", out);
req.getSession().setAttribute("inPutStream", in);
item.write(file);

}
}
} catch (FileUploadException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

@Override
public void init(ServletConfig config) throws ServletException {
// TODO Auto-generated method stub
super.init(config);
}

}

---------------
进度监听器


package com.dynastarter.sc.file.utils;



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

import org.apache.commons.fileupload.ProgressListener;

import com.dynastarter.sc.file.po.fileUploadStatus;

public class myProgressListener implements ProgressListener {
private HttpSession session;

public myProgressListener(HttpServletRequest req) {
session=req.getSession();
fileUploadStatus status = new fileUploadStatus();
session.setAttribute("status", status);
}

/* pBytesRead  到目前为止读取文件的比特数
* pContentLength 文件总大小
* pItems 目前正在读取第几个文件
*/
public void update(long pBytesRead, long pContentLength, int pItems) {
// TODO Auto-generated method stub
fileUploadStatus status = (fileUploadStatus) session.getAttribute("status");
System.out.println(pBytesRead);
System.out.println(pContentLength);
status.setPBytesRead(pBytesRead);
status.setPContentLength(pContentLength);
status.setPItems(pItems);
}

}



----------------
处理进度serlvet
package com.dynastarter.sc.file.utils;



import java.io.IOException;

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

import com.dynastarter.sc.file.po.fileUploadStatus;


public class progressServlet extends HttpServlet {
/**
*
*/
private static final long serialVersionUID = 1L;

public void doPost(HttpServletRequest request, HttpServletResponse response) {
HttpSession session = request.getSession();
fileUploadStatus status = (fileUploadStatus) session.getAttribute("status");
try {
if(status!=null){
response.reset();
response.getWriter().write("{\"pBytesRead\":"
+status.getPBytesRead()+",\"pContentLength\":"+status.getPContentLength()+"}");
System.out.println("{\"pBytesRead\":"
+status.getPBytesRead()+",\"pContentLength\":"+status.getPContentLength()+"}");
}

} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

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

}
}
--------------
web.xml
<servlet>
  <servlet-name>upload</servlet-name>
  <servlet-class>com.dynastarter.sc.file.utils.uploadServlet</servlet-class>
</servlet>
<servlet>
  <servlet-name>progressServlet</servlet-name>
  <servlet-class>com.dynastarter.sc.file.utils.progressServlet</servlet-class>
</servlet>

<servlet-mapping>
  <servlet-name>upload</servlet-name>
  <url-pattern>/upload</url-pattern>
</servlet-mapping>
<servlet-mapping>
  <servlet-name>progressServlet</servlet-name>
  <url-pattern>/getBar</url-pattern>
</servlet-mapping>

---------------------------
注意点如果系统中集成了struts2 或者spring security 请注意会uploadservlet的req会有点问题如果struts2的filter会把请求进行处理后封装的httpservletrequest传个servlet进行处理这样会得不到原始的请求 uploadservlet下面的处理会有问题
所有最好是把struts2的filter访问路径设置为*.do.如果有spring security则把两个servlet的请求路径进行过滤.

好了总结完毕