Servlet:htm+javascript+css+servlet (ajax)实现上传(能显示进度条)(二)
er to the client
* @throws ServletException if an error occurred
* @throws IOException if an error occurred
*/
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//禁用缓存,index.jsp后台会使用XmlHttpRequest调用本Servlet的doGet方法,从session中获取最新的上传数据情况
response.setHeader("Cache-Control", "no-store");
response.setHeader("Pragrma", "no-cache");
response.setDateHeader("Expires", 0);
response.setContentType("text/html;charset=utf-8");
UploadStatus status = (UploadStatus) request.getSession(true)
.getAttribute("uploadStatus");
if (status == null) {
response.getWriter().println("没有上传信息");
return;
}
long startTime = status.getStartTime();
long currentTime = System.currentTimeMillis();
// 已传输的时间 单位:s
long time = (currentTime - startTime) / 1000 + 1;
// 传输速度 单位:byte/s
double velocity = ((double) status.getBytesRead()) / (double) time;
// 估计总时间 单位:s
double totalTime = status.getContentLength() / velocity;
// 估计剩余时间 单位:s
double timeLeft = totalTime - time;
// 已完成的百分比
int percent = (int) (100 * (double) status.getBytesRead() / (double) status
.getContentLength());
// 已完成数 单位:M
double length = ((double) status.getBytesRead()) / 1024 / 1024;
// 总长度 单位:M
double totalLength = ((double) status.getContentLength()) / 1024 / 1024;
// 格式:百分比||已完成数(M)||文件总长度(M)||传输速率(K)||已用时间(s)||估计总时间(s)||估计剩余时间(s)||正在上传第几个文件
+ velocity + "||" + time + "||" + totalTime + "||" + timeLeft
+ "||" + status.getItems();
response.getWriter().println(value);
}
/**
* The doPost method of the servlet.
*
* This method is called when a form has its tag value method equals to post.
*
* @param request the request send by the client to the server
* @param response the response send by the server to the client
* @throws ServletException if an error occurred
* @throws IOException if an error occurred
*/
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
File file=null;
String description=null;
//设置响应格式(不设置请求格式,因为文件是二进制的,不能使用UTF-8格式化请求数据)
response.setContentType("text/html;charset=utf-8");
PrintWriter out=response.getWriter();
out.println("");
out.println("");
out.println("文件上传 ");
out.println("");
out.println("上传日志:
");
");
UploadStatus status=new UploadStatus();
UploadListener listener=new UploadListener(status);
/*
*
* 把 UploadStatus 放到 session 里,引用
返回与此请求关联的当前HttpSession,如果没有当前会话和创造是真实的,返回一个新的会话。
如果创建是假的,并要求有没有有效的HttpSession,这个方法返回null。
*/
request.getSession(true).setAttribute("uploadStatus", status);
//创建基于磁盘的工厂,针对大文件,临时文件将存储在磁盘