热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

文件上传---动作条

利用Apachecommonsfileupload上传文件,直接显示其完成的进度条。----示例代码源自《JAVAWEB王者归来》1首先要显示动作条要利用Ajax的异步请求,使得在

  利用Apache commons fileupload上传文件,直接显示其完成的进度条。----示例代码源自《JAVA WEB王者归来》

  1 首先要显示动作条要利用Ajax的异步请求,使得在没有完成时,不会刷新本页,而是局部的刷新。如果没有指定form的定向页面,默认是刷新本页,正常我们提交一个form刷新本页,在没有完成请求前是显示空白的网页,这里我们指定他刷新一个不显示的区域,就要用到form的属性target。

<iframe name=uploadiframe width=0 height=0>iframe>
    <form action="servlet/ProgressUploadServlet" method="post" enctype="multipart/form-data"
        target="uploadiframe" onsubmit="showStatus();">
        <input type="file" name="file1" style="width:350px;"/><br/>
        <input type="file" name="file2" style="width:350px;"/><br/>
        <input type="file" name="file3" style="width:350px;"/><br/>
        <input type="submit" value="submit" id="btnSubmit"/>    
    form> 

 

  2 我们创建一个status的bean,用来保存一些状态信息,比如名字,读取的长度,读取的字节大小,时间等等。

public class UploadStatus {
    private long bytesRead;
    private long contentLength;
    private int items;
    private long startTime = System.currentTimeMillis();
    public long getBytesRead() {
        return bytesRead;
    }
    public void setBytesRead(long bytesRead) {
        this.bytesRead = bytesRead;
    }
    public long getContentLength() {
        return contentLength;
    }
    public void setContentLength(long contentLength) {
        this.cOntentLength= contentLength;
    }
    public int getItems() {
        return items;
    }
    public void setItems(int items) {
        this.items = items;
    }
    public long getStartTime() {
        return startTime;
    }
    public void setStartTime(long startTime) {
        this.startTime = startTime;
    }
}

 

  3 创建一个监听器实时的获取状态信息

public class UploadListener implements ProgressListener {
    private UploadStatus status;
    public UploadListener(UploadStatus status){
        this.status = status;
    }
    public void update(long bytesRead,long contentLength,int items){
        status.setBytesRead(bytesRead);
        status.setContentLength(contentLength);
        status.setItems(items);
    }
}

 

  4 form表单用pos方法提交后,在doPost里面获取状态信息,保存到session中。在本页面,在自动用get方法读取session中的信息,返回给网页,网页动态的进行数据的显示。

  doPost

UploadStatus status = new UploadStatus();
        UploadListener listener = new UploadListener(status);
        request.getSession(true).setAttribute("uploadStatus",status);
        
        ServletFileUpload upload = new ServletFileUpload(new DiskFileItemFactory());
        
        upload.setProgressListener(listener);

  doGet

long startTime = status.getStartTime();
        long currentTime = System.currentTimeMillis();
        long time = (currentTime - startTime)/1000 + 1;
        
        double velocity = ((double)status.getBytesRead())/(double)time;
        
        double totalTime = status.getContentLength()/velocity;
        
        double timeLeft = totalTime - time;
        
        int percent = (int)(100*(double)status.getBytesRead()/(double)status.getContentLength());
        
        double length = ((double)status.getBytesRead())/1024/1024;
        
        double totalLength = ((double)status.getContentLength())/1024/1024;
        
        String value = percent +"||" + length + "||" +totalLength+"||"+
                        velocity+"||"+time+"||"+totalTime+"||"+timeLeft+"||"+status.getItems();
        
        response.getWriter().println(value);

js

 

全部代码:

progressFileupload.jsp

<%@ page language="java" import="java.util.*" pageEncoding="ISO-8859-1"%>
<%
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>My JSP 'progressFileupload.jsp' starting pagetitle>
    
    <meta http-equiv="pragma" content="no-cache">
    <meta http-equiv="cache-control" content="no-cache">
    <meta http-equiv="expires" content="0">    
    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
    <meta http-equiv="description" content="This is my page">
    
    <style type="text/css">
        #progressBar {width:400px;height:12px;background:#FFFFFF;border:1px solid #000000;padding:1px}
        #progressBarItem{width:30%;height:100%;background:#FF0000;}
    style>
  head>
  
  <body>
      <iframe name=uploadiframe width=0 height=0>iframe>
    <form action="servlet/ProgressUploadServlet" method="post" enctype="multipart/form-data"
        target="uploadiframe" onsubmit="showStatus();">
        <input type="file" name="file1" style="width:350px;"/><br/>
        <input type="file" name="file2" style="width:350px;"/><br/>
        <input type="file" name="file3" style="width:350px;"/><br/>
        <input type="submit" value="submit" id="btnSubmit"/>    
    form> 
    <div id="status" style="display:none;">
    uploadbar:
        <div id="progressBar"><div id="progressBarItem">div>div>
        <div id="statusInfo">div>
    div>
    <script type="text/Javascript">
        var finished = true;
        function $(obj){
            return document.getElementById(obj);
        }
        function showStatus(){
            finished = false;
            $('status').style.display = 'block';
            $('progressBarItem').style.width = '1%';
            $('btnSubmit').disabled = true;
            setTimeout("requestStatus()",1000);
        }
        function requestStatus(){
            if(finished) return;
            var req = createRequest();
            req.open("GET","servlet/ProgressUploadServlet");
            req.onreadystatechange = function(){callback(req);}
            
            req.send(null);
            setTimeout("requestStatus()",1000);
        }
        function createRequest(){
            if(window.XMLHttpRequest){
                return new XMLHttpRequest();
            }else{
                try{
                    return new ActiveXObject("Msxml2.XMLHTTP");
                }catch(e){
                    return new ActiveXObject("Microsoft.XMLHTTP");
                }
            }
            return null;
        }
        function callback(req){
            if(req.readyState == 4){
                if(req.status != 200){
                    debug("error! req.status:"+req.status+"");
                    return ;
                }
                debug("status.jsp return value:"+req.responseText);
                var ss = req.responseText.split("||");
                $('progressBarItem').style.width = ''+ss[0]+'%';
                $('statusInfo').innerHTML = 'end of total:'+ss[0] +'%
'+ 'sucess of numbers:'+ss[1]+'
'+ 'length of file:'+ss[2]+'
'+ 'velocity of trans:'+ss[3]+'
'+ 'the time used:'+ss[4]+'
'+ 'total time:'+ss[5]+'
'+ 'other time:'+ss[6]+'
'+ 'which is translating:'+ss[7]; if(ss[1] == ss[2]){ finished = true; $('statusInfo').innerHTML += "


have done!
"; $('btnSubmit').disabled = false; } } } function debug(obj){ var div = document.createElement("DIV"); div.innerHTML = "[debug]:"+obj; document.body.appendChild(div); } script> body> html>
View Code

UploadStatus.java

package com.test.temp;

public class UploadStatus {
    private long bytesRead;
    private long contentLength;
    private int items;
    private long startTime = System.currentTimeMillis();
    public long getBytesRead() {
        return bytesRead;
    }
    public void setBytesRead(long bytesRead) {
        this.bytesRead = bytesRead;
    }
    public long getContentLength() {
        return contentLength;
    }
    public void setContentLength(long contentLength) {
        this.cOntentLength= contentLength;
    }
    public int getItems() {
        return items;
    }
    public void setItems(int items) {
        this.items = items;
    }
    public long getStartTime() {
        return startTime;
    }
    public void setStartTime(long startTime) {
        this.startTime = startTime;
    }
}
View Code

UploadListener.java

package com.test.temp;

import org.apache.commons.fileupload.ProgressListener;

public class UploadListener implements ProgressListener {
    private UploadStatus status;
    public UploadListener(UploadStatus status){
        this.status = status;
    }
    public void update(long bytesRead,long contentLength,int items){
        status.setBytesRead(bytesRead);
        status.setContentLength(contentLength);
        status.setItems(items);
    }
}
View Code

PorgressUploadServlet.java

package com.test.hello;

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

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.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import com.test.temp.UploadListener;
import com.test.temp.UploadStatus;

public class ProgressUploadServlet extends HttpServlet {

    /**
     * Constructor of the object.
     */
    public ProgressUploadServlet() {
        super();
    }

    /**
     * Destruction of the servlet. 
*/ public void destroy() { super.destroy(); // Just puts "destroy" string in log // Put your code here } /** * The doGet method of the servlet.
* * This method is called when a form has its tag value method equals to get. * *
@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 doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setHeader("Cache-Control","no-store"); response.setHeader("Pragrma","no-cache"); response.setDateHeader("Expires",0); UploadStatus status = (UploadStatus) request.getSession(true).getAttribute("uploadStatus"); if(status == null){ response.getWriter().println("没有上传信息"); return; } long startTime = status.getStartTime(); long currentTime = System.currentTimeMillis(); long time = (currentTime - startTime)/1000 + 1; double velocity = ((double)status.getBytesRead())/(double)time; double totalTime = status.getContentLength()/velocity; double timeLeft = totalTime - time; int percent = (int)(100*(double)status.getBytesRead()/(double)status.getContentLength()); double length = ((double)status.getBytesRead())/1024/1024; double totalLength = ((double)status.getContentLength())/1024/1024; String value = percent +"||" + length + "||" +totalLength+"||"+ 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 { UploadStatus status = new UploadStatus(); UploadListener listener = new UploadListener(status); request.getSession(true).setAttribute("uploadStatus",status); ServletFileUpload upload = new ServletFileUpload(new DiskFileItemFactory()); upload.setProgressListener(listener); try{ List itemList = upload.parseRequest(request); for(Iterator it = itemList.iterator();it.hasNext();){ FileItem item = (FileItem)it.next(); if(item.isFormField()){ System.out.println("FormField:"+item.getFieldName()+"="+item.getString()); }else{ System.out.println("File:"+item.getName()); String fileName = item.getName().replace("/","\\"); fileName = fileName.substring(fileName.lastIndexOf("\\")); File saved = new File("D:\\upload_temp",fileName); saved.getParentFile().mkdirs(); InputStream ins = item.getInputStream(); OutputStream ous = new FileOutputStream(saved); byte[] tmp = new byte[1024]; int len = -1; while((len = ins.read(tmp)) != -1){ ous.write(tmp,0,len); } ous.close(); ins.close(); response.getWriter().println("已保存文件:"+saved); } } }catch(Exception e){ response.getWriter().println("上传发生错误:"+e.getMessage()); } // response.setContentType("text/html"); // PrintWriter out = response.getWriter(); // out // .println("//W3C//DTD HTML 4.01 Transitional//EN\">"); // out.println(""); // out.println(" "); // out.println(" "); // out.print(" This is "); // out.print(this.getClass()); // out.println(", using the POST method"); // out.println(" "); // out.println(""); // out.flush(); // out.close(); } /** * Initialization of the servlet.
* *
@throws ServletException if an error occurs */ public void init() throws ServletException { // Put your code here } }
View Code

web.xml

xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" 
    xmlns="http://java.sun.com/xml/ns/javaee" 
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
    http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
  <servlet>
    <description>This is the description of my J2EE componentdescription>
    <display-name>This is the display name of my J2EE componentdisplay-name>
    <servlet-name>PostServletservlet-name>
    <servlet-class>com.test.hello.PostServletservlet-class>
  servlet>
  <servlet>
    <description>This is the description of my J2EE componentdescription>
    <display-name>This is the display name of my J2EE componentdisplay-name>
    <servlet-name>testservlet-name>
    <servlet-class>com.test.hello.testservlet-class>
  servlet>
  <servlet>
    <description>This is the description of my J2EE componentdescription>
    <display-name>This is the display name of my J2EE componentdisplay-name>
    <servlet-name>UploadServletservlet-name>
    <servlet-class>com.test.hello.UploadServletservlet-class>
  servlet>
  <servlet>
    <description>This is the description of my J2EE componentdescription>
    <display-name>This is the display name of my J2EE componentdisplay-name>
    <servlet-name>ProgressUploadServletservlet-name>
    <servlet-class>com.test.hello.ProgressUploadServletservlet-class>
  servlet>



  <servlet-mapping>
    <servlet-name>PostServletservlet-name>
    <url-pattern>/servlet/PostServleturl-pattern>
  servlet-mapping>
  <servlet-mapping>
    <servlet-name>testservlet-name>
    <url-pattern>/servlet/testurl-pattern>
  servlet-mapping>
  <servlet-mapping>
    <servlet-name>UploadServletservlet-name>
    <url-pattern>/servlet/UploadServleturl-pattern>
  servlet-mapping>
  <servlet-mapping>
    <servlet-name>ProgressUploadServletservlet-name>
    <url-pattern>/servlet/ProgressUploadServleturl-pattern>
  servlet-mapping>
  <welcome-file-list>
    <welcome-file>index.jspwelcome-file>
  welcome-file-list>
web-app>
View Code

运行结果:

  


推荐阅读
  • Java序列化对象传给PHP的方法及原理解析
    本文介绍了Java序列化对象传给PHP的方法及原理,包括Java对象传递的方式、序列化的方式、PHP中的序列化用法介绍、Java是否能反序列化PHP的数据、Java序列化的原理以及解决Java序列化中的问题。同时还解释了序列化的概念和作用,以及代码执行序列化所需要的权限。最后指出,序列化会将对象实例的所有字段都进行序列化,使得数据能够被表示为实例的序列化数据,但只有能够解释该格式的代码才能够确定数据的内容。 ... [详细]
  • 标题: ... [详细]
  • 本文讨论了在shiro java配置中加入Shiro listener后启动失败的问题。作者引入了一系列jar包,并在web.xml中配置了相关内容,但启动后却无法正常运行。文章提供了具体引入的jar包和web.xml的配置内容,并指出可能的错误原因。该问题可能与jar包版本不兼容、web.xml配置错误等有关。 ... [详细]
  • Java如何导入和导出Excel文件的方法和步骤详解
    本文详细介绍了在SpringBoot中使用Java导入和导出Excel文件的方法和步骤,包括添加操作Excel的依赖、自定义注解等。文章还提供了示例代码,并将代码上传至GitHub供访问。 ... [详细]
  • 本文介绍了解决java开源项目apache commons email简单使用报错的方法,包括使用正确的JAR包和正确的代码配置,以及相关参数的设置。详细介绍了如何使用apache commons email发送邮件。 ... [详细]
  • Java太阳系小游戏分析和源码详解
    本文介绍了一个基于Java的太阳系小游戏的分析和源码详解。通过对面向对象的知识的学习和实践,作者实现了太阳系各行星绕太阳转的效果。文章详细介绍了游戏的设计思路和源码结构,包括工具类、常量、图片加载、面板等。通过这个小游戏的制作,读者可以巩固和应用所学的知识,如类的继承、方法的重载与重写、多态和封装等。 ... [详细]
  • PHP图片截取方法及应用实例
    本文介绍了使用PHP动态切割JPEG图片的方法,并提供了应用实例,包括截取视频图、提取文章内容中的图片地址、裁切图片等问题。详细介绍了相关的PHP函数和参数的使用,以及图片切割的具体步骤。同时,还提供了一些注意事项和优化建议。通过本文的学习,读者可以掌握PHP图片截取的技巧,实现自己的需求。 ... [详细]
  • 本文介绍了RPC框架Thrift的安装环境变量配置与第一个实例,讲解了RPC的概念以及如何解决跨语言、c++客户端、web服务端、远程调用等需求。Thrift开发方便上手快,性能和稳定性也不错,适合初学者学习和使用。 ... [详细]
  • 从零学Java(10)之方法详解,喷打野你真的没我6!
    本文介绍了从零学Java系列中的第10篇文章,详解了Java中的方法。同时讨论了打野过程中喷打野的影响,以及金色打野刀对经济的增加和线上队友经济的影响。指出喷打野会导致线上经济的消减和影响队伍的团结。 ... [详细]
  • Imtryingtofigureoutawaytogeneratetorrentfilesfromabucket,usingtheAWSSDKforGo.我正 ... [详细]
  • 大数据Hadoop生态(20)MapReduce框架原理OutputFormat的开发笔记
    本文介绍了大数据Hadoop生态(20)MapReduce框架原理OutputFormat的开发笔记,包括outputFormat接口实现类、自定义outputFormat步骤和案例。案例中将包含nty的日志输出到nty.log文件,其他日志输出到other.log文件。同时提供了一些相关网址供参考。 ... [详细]
  • AFNetwork框架(零)使用NSURLSession进行网络请求
    本文介绍了AFNetwork框架中使用NSURLSession进行网络请求的方法,包括NSURLSession的配置、请求的创建和执行等步骤。同时还介绍了NSURLSessionDelegate和NSURLSessionConfiguration的相关内容。通过本文可以了解到AFNetwork框架中使用NSURLSession进行网络请求的基本流程和注意事项。 ... [详细]
  • Apache Shiro 身份验证绕过漏洞 (CVE202011989) 详细解析及防范措施
    本文详细解析了Apache Shiro 身份验证绕过漏洞 (CVE202011989) 的原理和影响,并提供了相应的防范措施。Apache Shiro 是一个强大且易用的Java安全框架,常用于执行身份验证、授权、密码和会话管理。在Apache Shiro 1.5.3之前的版本中,与Spring控制器一起使用时,存在特制请求可能导致身份验证绕过的漏洞。本文还介绍了该漏洞的具体细节,并给出了防范该漏洞的建议措施。 ... [详细]
  • 本文介绍了禅道作为一款国产开源免费的测试管理工具的特点和功能,并提供了禅道的搭建和调试方法。禅道是一款B/S结构的项目管理工具,可以实现组织管理、后台管理、产品管理、项目管理和测试管理等功能。同时,本文还介绍了其他软件测试相关工具,如功能自动化工具和性能自动化工具,以及白盒测试工具的使用。通过本文的阅读,读者可以了解禅道的基本使用方法和优势,从而更好地进行测试管理工作。 ... [详细]
  • 项目运行环境配置及可行性分析
    本文介绍了项目运行环境配置的要求,包括Jdk1.8、Tomcat7.0、Mysql、HBuilderX等工具的使用。同时对项目的技术可行性、操作可行性、经济可行性、时间可行性和法律可行性进行了分析。通过对数据库的设计和功能模块的设计,确保系统的完整性和安全性。在系统登录、系统功能模块、管理员功能模块等方面进行了详细的介绍和展示。最后提供了JAVA毕设帮助、指导、源码分享和调试部署的服务。 ... [详细]
author-avatar
mobiledu2502881467
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有