文件上传---动作条

  利用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

<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] +'%<br/>'+
                'sucess of numbers:'+ss[1]+'<br/>'+
                'length of file:'+ss[2]+'<br/>'+
                'velocity of trans:'+ss[3]+'<br/>'+
                'the time used:'+ss[4]+'<br/>'+
                'total time:'+ss[5]+'<br/>'+
                'other time:'+ss[6]+'<br/>'+
                'which is translating:'+ss[7];

                if(ss[1] == ss[2]){
                    finished = true;
                    $('statusInfo').innerHTML += "<br/><br/><br/>have done!";
                    $('btnSubmit').disabled = false;

                }
            }
        }
        function debug(obj){
            var div = document.createElement("DIV");
            div.innerHTML = "[debug]:"+obj;
            document.body.appendChild(div);
        }
    </script>

全部代码:

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 page</title>

    <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">
    <!--
    <link rel="stylesheet" type="text/css" href="styles.css">
    -->
    <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] +'%<br/>'+
                'sucess of numbers:'+ss[1]+'<br/>'+
                'length of file:'+ss[2]+'<br/>'+
                'velocity of trans:'+ss[3]+'<br/>'+
                'the time used:'+ss[4]+'<br/>'+
                'total time:'+ss[5]+'<br/>'+
                'other time:'+ss[6]+'<br/>'+
                'which is translating:'+ss[7];

                if(ss[1] == ss[2]){
                    finished = true;
                    $('statusInfo').innerHTML += "<br/><br/><br/>have done!";
                    $('btnSubmit').disabled = false;

                }
            }
        }
        function debug(obj){
            var div = document.createElement("DIV");
            div.innerHTML = "[debug]:"+obj;
            document.body.appendChild(div);
        }
    </script>
  </body>
</html>

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;
    }
}

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);
    }
}

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. <br>
     */
    public void destroy() {
        super.destroy(); // Just puts "destroy" string in log
        // Put your code here
    }

    /**
     * The doGet method of the servlet. <br>
     *
     * 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. <br>
     *
     * 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("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">");
//        out.println("<HTML>");
//        out.println("  <HEAD><TITLE>A Servlet</TITLE></HEAD>");
//        out.println("  <BODY>");
//        out.print("    This is ");
//        out.print(this.getClass());
//        out.println(", using the POST method");
//        out.println("  </BODY>");
//        out.println("</HTML>");
//        out.flush();
//        out.close();
    }

    /**
     * Initialization of the servlet. <br>
     *
     * @throws ServletException if an error occurs
     */
    public void init() throws ServletException {
        // Put your code here
    }

}

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 component</description>
    <display-name>This is the display name of my J2EE component</display-name>
    <servlet-name>PostServlet</servlet-name>
    <servlet-class>com.test.hello.PostServlet</servlet-class>
  </servlet>
  <servlet>
    <description>This is the description of my J2EE component</description>
    <display-name>This is the display name of my J2EE component</display-name>
    <servlet-name>test</servlet-name>
    <servlet-class>com.test.hello.test</servlet-class>
  </servlet>
  <servlet>
    <description>This is the description of my J2EE component</description>
    <display-name>This is the display name of my J2EE component</display-name>
    <servlet-name>UploadServlet</servlet-name>
    <servlet-class>com.test.hello.UploadServlet</servlet-class>
  </servlet>
  <servlet>
    <description>This is the description of my J2EE component</description>
    <display-name>This is the display name of my J2EE component</display-name>
    <servlet-name>ProgressUploadServlet</servlet-name>
    <servlet-class>com.test.hello.ProgressUploadServlet</servlet-class>
  </servlet>

  <servlet-mapping>
    <servlet-name>PostServlet</servlet-name>
    <url-pattern>/servlet/PostServlet</url-pattern>
  </servlet-mapping>
  <servlet-mapping>
    <servlet-name>test</servlet-name>
    <url-pattern>/servlet/test</url-pattern>
  </servlet-mapping>
  <servlet-mapping>
    <servlet-name>UploadServlet</servlet-name>
    <url-pattern>/servlet/UploadServlet</url-pattern>
  </servlet-mapping>
  <servlet-mapping>
    <servlet-name>ProgressUploadServlet</servlet-name>
    <url-pattern>/servlet/ProgressUploadServlet</url-pattern>
  </servlet-mapping>
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
</web-app>

运行结果:

  

本文转自博客园xingoo的博客,原文链接:文件上传---动作条,如需转载请自行联系原博主。

时间: 2024-11-03 23:48:01

文件上传---动作条的相关文章

服务器-我这样做asp.net异步文件上传进度条

问题描述 我这样做asp.net异步文件上传进度条 前台两个请求 1.上传文件的请求 2.获取上传进度的请求 1. $("#ufrm").ajaxSubmit({ url: "ReceivFile.ashx", type: "post", success: function (data) { ... 2. $.ajax({ type: "post", url: "Filepro.aspx", data: {

HTML5 Ajax文件上传进度条如何显示_AJAX相关

原本打算使用jquery插件进行异步文件上传,比如uploadfy但是需要额外的支持,也有人用iframe模仿异步上传机制,感觉都比较别扭.因为项目不考虑低版本浏览器,所以决定用html5实现.下面只是一个简单的demo,具体样式需要自己去做. 后台基于strut2进行文件处理,具体因项目而定.只是要注意设置文件大小的限制.  <constant name="struts.multipart.maxSize" value="52428800"/>这个配置

PHP利用APC模块实现文件上传进度条的方法_php技巧

本文实例讲述了PHP利用APC模块实现文件上传进度条的方法.分享给大家供大家参考.具体分析如下: 以前的php5.2之前的版本是不能可使用APC模块的,因为之前的压根就没有这个APC模块,如果想使用APC模块实现上传进度条我们必须是php5.2或更高版本. 从5.2开始APC加入了一个叫APC_UPLOAD_PROGRESS的东东,解决了困扰大家已久的进度条问题.并且它把原来的上传时把临时文件全部缓存到内存改成了当临时文件达到设定值时就自动保存到硬盘,有效地改善了内存利用状况. 它的作用原理是在

php ajax实现文件上传进度条_php技巧

本实例是关于php文件上传时进度条的实现,主要采用ajax技术,另外还运用了html5,有需要的朋友可以研究一下. 本实例有两个文件: upload_form.html: <!DOCTYPE html> <html> <head> <script> function _(el){ return document.getElementById(el); } function uploadFile(){ var file = _("file1"

PHP中使用Session配合Javascript实现文件上传进度条功能_php技巧

Web应用中常需要提供文件上传的功能.典型的场景包括用户头像上传.相册图片上传等.当需要上传的文件比较大的时候,提供一个显示上传进度的进度条就很有必要了. 在PHP 5.4以前,实现这样的进度条并不容易,主要有三种方法: 1.使用Flash, Java, ActiveX 2.使用PHP的APC扩展 3.使用HTML5的File API 第一种方法依赖第三方的浏览器插件,通用性不足,且易带来安全隐患.不过由于Flash的使用比较广泛,因此还是有很多网站使用Flash作为解决方案. 第二种方法的不足

PHP Session和Javascript实现文件上传进度条

在PHP 5.4以前,实现这样的进度条并不容易,主要有三种方法: 1.使用Flash, Java, ActiveX 2.使用PHP的APC扩展 3.使用HTML5的File API 第一种方法依赖第三方的浏览器插件,通用性不足,且易带来安全隐患.不过由于Flash的使用比较广泛,因此还是有很多网站使用Flash作为解决方案. 第二种方法的不足在于,它需要安装PHP的APC扩展库,要求用户能够控制服务器端的配置.另外,如果安装APC仅仅是为了实现一个上传进度条,那么显然有点杀鸡用牛刀的意思. 第三

文件上传进度条php代码

目前我知道的方法有两种,一种是使用php的创始人 rasmus lerdorf 写的apc扩展模块来实现(http://pecl.php.net/package/apc),另外一种方法是使用pecl扩展模块uploadprogress实现(http://pecl.php.net/package/uploadprogress) 我这里举两个分别实现的例子供参考,更灵活的应用根据自己需要来修改. apc实现方法: 安装apc,参照官方文档安装,可以使用pecl模块安装方法快速简捷,这里不说明 配置p

asp.net 文件上传进度条实现代码

asp教程.net 文件上传进度条实现代码 index.htm就是文件上传页面,提交form给uploadhandler目录下的default.aspx,以实现文件上传. progresshandler目录下三个文件为abort.ashx.genericguid.ashx,handler.ashx功能分别为:根据guid取消正在上传的文件,生成guid,根据guid获取上传信息. 第一步:建立index.htm页面,这个上传页面,需要注意的就是需要一个隐藏的iframe,并且名字为form提交的

jQuery实现简单的文件上传进度条效果_jquery

本文实例讲述了jQuery实现文件上传进度条效果的代码.分享给大家供大家参考.具体如下: 运行效果截图如下: 具体代码如下: <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>upload</title> <link rel="stylesheet" type="text/css" href=&quo