项目中要用到上传.同时要有进度条提示 从网上找了些解决方案自己学习了下.做个总结:
上传过程中使用到的是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的请求路径进行过滤.
好了总结完毕
分享到:
相关推荐
ajax上传文件,ajax实现进度条,及springMvc上传文件实现进度条
带进度条的附件上传,可以根据自己的要求修改里面的方法。
ssh2(struts2+spring2.5+hibernate3.3+ajax)带进度条文件上传(封装成标签)
java写的带进度条的Ajax多文件上传,直接以前看过一个Ajax写的太复杂了,改进了一下,通俗易懂,可以实时看上传进度,上传速度
使用java+ajax技术 上传文件带进度条
java+ajax带进度条的上传, 改进过后的,不会报错,直接运行
Java中使用Ajax、Jquery带进度条文件上传,需要的下吧,忙了我一个下午噢,累死了。
ajax异步上传 异步上传 进度条 ajax进度条 上传进度条 不是swfUpload
java使用ajax多文件上传,并显示上传进度条和上传速度
要实现进度条的显示,就要知道两个参数,上传的大小和总文件的大小 重写的解析器提供了一个上传过程事件,在上传过程中不断触发,然后用已上传的大 小/总大小,计算上传的百分比,然后将此数据缓存起来,前端发送异步...
一个基于Servlet+ajax的进度条,可用于上传,下载等加载比较大的资源时使用
spring+velocity+ajax带进度条上传文件,上传显示文件的状态。
使用Servlet、jsp、jQuery、ajax实现模拟数据导入,文件上传进度条功能。
java带进度条的异步上传,采用servlet、ajax 可以用来学习交流使用
ajax 文件 上传 进度条
非常漂亮ajax 无刷新上传 带进度条的源代码。下载后直接拷贝到程序下 启动就可运行 !
ajax版自定义上传文件数量+进度条+JAVA+Servlet QQ群:14622422 WEB开发性感地带■■ 高洪岩版 ajax版自定义上传文件数量+进度条+JAVA+Servlet.
带进度条的文件上传(java+ajax,附源码)
Ajax-upload 的JSP实现源码,运行于JSP环境,含相关的JAVA源代码,学习Java比较不错,同时本程序实现带上传进度条上传图片、文件等,上传程序是大家经常用到的模块,你可将本模块摘录出来用到你的JSP项目中。
带进度条的java上传下载源码(java+ajax)