servlet+jquery实现文件上传进度条示例代码

现在文件的上传,特别是大文件上传,都需要进度条,让客户知道上传进度。

本文简单记录下如何弄进度条,以及一些上传信息,比如文件的大小,上传速度,预计剩余时间等一些相关信息。代码是匆忙下简单写的,一些验证没做,或代码存在一些隐患,不严谨的地方。本文代码只供参考。

进度条的样式多种多样,有些网站弄得非常绚烂漂亮。本文UI端不太懂,只会一些简单的基本的css而已,所以进度条弄得不好看。本文侧重的给读者提供一个参考,一个实现思路而已。

注:由于jQuery版本用的是2.1.1,所以如果跑本例子源码,请用IE9以上或火狐、谷歌浏览器测试。

接收文件上传的servlet

UploadFileServlet.Java

package com.fei.servlet; 

import java.io.IOException;
import java.util.Date;
import java.util.Map; 

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

import com.fei.util.FileUploadUtil; 

public class UploadFileServlet extends HttpServlet { 

  private static final long serialVersionUID = 1L; 

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

  public void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    try {
      long start = System.currentTimeMillis();
      System.out.println("开始上传文件........." );
      Map<String, String> params = FileUploadUtil.upload(request);
      System.out.println("文件上传完成........." );
      System.out.println("文件上次用时:"+(System.currentTimeMillis()-start)+"毫秒");
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
}

将上传文件进行下载到服务器的处理

FileUploadUtil.java

package com.fei.util; 

import java.io.File;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map; 

import javax.servlet.http.HttpServletRequest; 

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

public class FileUploadUtil { 

  /**
   * 文件上传保存路径
   */
  private static final String SAVE_FILEPATH = "/fileupload/";
  /**
   * 文件上传临时保存路径
   */
  private static final String SAVE_FILE_TMPPATH = "/fileupload/tmp/";
  /**
   * 上传文件的最大值M
   */
  private static final int MAX_FILE_SIZE = 100*1024*1024;
  /**
   * 文件数据在内存中超过多少M后,就写入临时文件
   */
  private static final int THRESHOLD_SIZE = 2*1024*1024; 

  private static final String ENCODING = "UTF-8"; 

  /**
   * 处理文件上传的表单
   * 下载文件,并返回文件名称及普通表单域中其它属性值
   * 获取文件名
   */
  public static Map<String,String> upload(HttpServletRequest request)throws Exception{
    Map<String,String> params = new HashMap<String, String>(); 

    String savePath = request.getSession().getServletContext()
        .getRealPath(SAVE_FILEPATH)+ File.separator;
    String savePathTemp = request.getSession().getServletContext()
        .getRealPath(SAVE_FILE_TMPPATH)+ File.separator; 

    File saveFileTempDir = new File(savePathTemp); 

    DiskFileItemFactory factory = new DiskFileItemFactory();
    //当内存中文件数据达到THRESHOLD_SIZE后,就写入临时文件中,避免上传大文件时,消化太多内存
    factory.setSizeThreshold(THRESHOLD_SIZE);
    factory.setRepository(saveFileTempDir); 

    ServletFileUpload upload = new ServletFileUpload(factory);
    upload.setHeaderEncoding(ENCODING);
    upload.setSizeMax(MAX_FILE_SIZE); 

    FileUploadInfo fileUploadInfo = new FileUploadInfo();
    upload.setProgressListener(new FileUploadListener(fileUploadInfo));
    request.getSession().setAttribute("uploadInfo", fileUploadInfo); 

    List items = upload.parseRequest(request);
    Iterator iter = items.iterator();
    int fileNum = 1;
    while(iter.hasNext()){
      FileItem item = (FileItem) iter.next();
      if (item.isFormField()) {//普通表单域
        params.put(item.getFieldName(), item.getString());
      } else {
        String fileName = item.getName().replace("/", "\\");
        int i = fileName.lastIndexOf("\\");
        fileName = fileName.substring(i+1);
        //避免重复
        fileName = System.currentTimeMillis() + fileName; 

        File uploadedFile = new File(savePath + fileName);
        item.write(uploadedFile); 

        params.put("fileName0"+fileNum, fileName);
        fileNum ++; 

      }
    } 

    return params;
  } 

} 

class FileUploadListener implements ProgressListener{ 

  FileUploadInfo fileUploadInfo = null; 

  public FileUploadListener(FileUploadInfo fileUploadInfo) {
    this.fileUploadInfo = fileUploadInfo;
  } 

  @Override
  public void update(long uploadSize, long totalSize, int itemNum) {
    this.fileUploadInfo.setTotalSize(totalSize);
    this.fileUploadInfo.setUploadSize(uploadSize); 

  } 

}

上传文件的一些信息

FileUploadInfo.java

package com.fei.util; 

public class FileUploadInfo { 

  private final int K = 1024; 

  private final int M = K * 1024; 

  /**
   * 总大小
   */
  private long totalSize;
  /**
   * 开始上传时间
   */
  private long startTime = System.currentTimeMillis();
  /**
   * 已上传多少
   */
  private long uploadSize; 

  /**
   * 上传速度(K/S)
   */
  public double getUploadSpeed_K(){
    long currentTime = System.currentTimeMillis();
    long usedTime = currentTime - startTime;
    if(usedTime == 0.0){
      return 0.0;
    }
    return getUploadSize_K()/usedTime*1000d;
  }
  /**
   * 获取已上传百分比
   * @return
   */
  public double getUploadPercent(){
    return (getUploadSize()*1.00/getTotalSize())*100d;
  }
  /**
   * 剩余时间(s)
   * @return
   */
  public double getRemainTime(){
    double speedKB = getUploadSpeed_K();
    if(speedKB<= 0.00){
      return -1d;
    }
    return (getTotalSize_K() - getUploadSize_K())/speedKB;
  }
  /**
   * 已上传时间
   * @return
   */
  public double getUseTime(){
    return (System.currentTimeMillis() - startTime)/1000d;
  } 

  public long getTotalSize() {
    return totalSize;
  } 

  public double getTotalSize_K(){
    return getTotalSize()*1.0/K;
  } 

  public double getTotalSize_M(){
    return getTotalSize()*1.0/M;
  } 

  public long getUploadSize() {
    return uploadSize;
  } 

  public double getUploadSize_K(){
    return getUploadSize()/K;
  } 

  public double getUploadSize_M(){
    return getUploadSize()/M;
  } 

  public void setTotalSize(long totalSize) {
    this.totalSize = totalSize;
  } 

  public void setUploadSize(long uploadSize) {
    this.uploadSize = uploadSize;
  } 

  private String double2String(double d){
    return String.format("%.2f", d);
  } 

  public String toString(){
    return "{"+
        "'totalSize':'"+double2String(getTotalSize_M())+"M',"+
        "'uploadSize':'"+double2String(getUploadSize_M())+"M',"+
        "'uploadSpeed':'"+double2String(getUploadSpeed_K())+"KB/s',"+
        "'uploadPrecent':'"+double2String(getUploadPercent())+"',"+
        "'remainTime':'"+(getRemainTime()<0?"未知":double2String(getRemainTime()))+"s"+"',"+
        "'useTime':'"+double2String(getUseTime())+"s' "+
        "}";
  }
}

读取文件上传进度的servlet

UploadFileProgressServlet.java

package com.fei.servlet; 

import java.io.IOException; 

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

import com.fei.util.FileUploadInfo; 

public class UploadFileProgressServlet extends HttpServlet { 

  private static final long serialVersionUID = 1L; 

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

  public void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    String responseContent = ""; 

    Object obj = request.getSession().getAttribute("uploadInfo");
    if(obj == null){
      responseContent = "{'data':'NoData'}";
    }else{
      FileUploadInfo uploadInfo = (FileUploadInfo)obj;
      responseContent = uploadInfo.toString();
      if(uploadInfo.getUploadPercent()== 100.0){
        request.getSession().setAttribute("uploadInfo", null);
      }
    }
    System.out.println("文件上次情况:"+responseContent);
    response.getWriter().print(responseContent);
  }
}

前台页面upload2.html

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<script src="js/jquery-2.1.1.js" type="text/javascript"></script> 

<script >
var falseNum = 0;
$(document).ready(function(){
  $('#subbut').bind('click',
      function(){
        $('#fForm').submit();
        var eventFun = function(){
          $.ajax({
            type: 'GET',
            url: '/uploadtest/UploadFileProgressServlet.do',
            data: {},
            dataType: 'text',
            success : function(resData){
              //如果10次都失败,那就不要继续访问了
              if(falseNum > 10){
               window.clearInterval(intId);
               return;
              }
              var obj = eval("("+resData+")");
              if(obj.data == 'NoData'){
                falseNum ++ ;
                return;
              }
              $("#graphbox").css('display','block');
              $(".progressbar").css('width',obj.uploadPrecent+'%');
              $("#uploadPer").html(obj.uploadPrecent+'%');
              $("#progressInfo").html('总大小:'+obj.totalSize
                  +',速度:'+obj.uploadSpeed
                  +'%,剩余时间:'+obj.remainTime+',已用时间:'+obj.useTime);
              if(obj.uploadPrecent == 100){
                window.clearInterval(intId);
                $("#progressInfo").html("上传成功!");
              }
        }});};
        var intId = window.setInterval(eventFun,500);
  });
});
</script>
<style>
#graphbox{
border:1px solid #e7e7e7;
padding:5px;
width:350px;
background-color:#f8f8f8;
margin:5px 0;
display:none;
}
.graph{
position:relative;
background-color:#F0EFEF;
border:1px solid #cccccc;
padding:2px;
font-size:10px;
font-weight:500;
}
.graph .progressbar{
position:relative;
text-align:right;
color:#ffffff;
height:10px;
line-height:10px;
font-family:Arial;
display:block;
}
.graph .progressbar{background-color:#66CC33;} 

</style>
</head>
<body>
    <form id='fForm' class="form-actions form-horizontal" action="/uploadtest/UploadFileServlet.do"
       encType="multipart/form-data" target="uploadf" method="post">
         <div class="control-group">
          <label class="control-label">上传文件:</label>
          <div class="controls">
            <input type="file" name="file" style="width:350px"></br>
            <input type="file" name="file2" style="width:350px"></br>
            <button type="button" id="subbut" class="btn">上传</button>
          </div>
          <div id="graphbox">
            <div class="graph">
            <span class="progressbar" style="width:0%;"><span id="uploadPer"></span></span>
            </div>
          </div>
          <div id='progressInfo'>
          </div>
        </div>
    </form>
    <iframe name="uploadf" style="display:none"></iframe>
</body>
</html>

将项目部署到tomcat(或其他web容器),访问http://172.16.126.128:8080/uploadtest/upload2.html

效果:

代码下载:demo

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持我们。

(0)

相关推荐

  • Servlet实现多文件上传功能

    一.Servlet实现文件上传,需要添加第三方提供的jar包 下载地址: 1) commons-fileupload-1.2.2-bin.zip : 点击打开链接 2) commons-io-2.3-bin.zip :  点击打开链接 接着把这两个jar包放到 lib文件夹下: 二.文件上传的表单提交方式必须是POST方式 编码类型:enctype="multipart/form-data",默认是 application/x-www-form-urlencoded 比如:<fo

  • Servlet实现简单文件上传功能

    本文实例为大家分享了Servlet文件上传的具体代码,供大家参考,具体内容如下 两点要素: 1.表单提交方式必须是post 2.enctype一定要是multipart/form-data. enctype的默认值是application/x-www-form-urlencoded, 这种编码格式只支持键值对的数据,?键=值&键=值,只能是字符串,无法传输文件. multipart/form-data这种编码可以上传文件 需要的jar包: 实现: import java.io.BufferedI

  • SpringMVC + servlet3.0 文件上传的配置和实现代码

    简单几步,实现SpringMVC+servlet3.0文件上传功能: 第一步:配置web.xml文件中的servlet,添加multipart-config: <!-- SpringMVC --> <servlet> <servlet-name>myWeb</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-clas

  • Android中发送Http请求(包括文件上传、servlet接收)的实例代码

    复制代码 代码如下: /*** 通过http协议提交数据到服务端,实现表单提交功能,包括上传文件* @param actionUrl 上传路径 * @param params 请求参数 key为参数名,value为参数值 * @param file 上传文件 */public static void postMultiParams(String actionUrl, Map<String, String> params, FormBean[] files) {try {PostMethod p

  • java基于servlet实现文件上传功能解析

    最近项目需要做一个文件上传功能,做完了分享下,顺带当做笔记. 上传功能用后台用java实现,前端主要是js的ajax实现.后台还加入定时删除临时文件. 效果如图 首先是上传功能的主要类,下面是代码 package util.upload; import java.io.File; import java.io.IOException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Iterat

  • java基于servlet使用组件smartUpload实现文件上传

    文件上传在web应用中是非常常见的,现在我就介绍下基于servlet的文件上传,基于Struts2的文件上传可以看: 页面端代码: <%@ page language="java" import="java.util.*" pageEncoding="GBK"%> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <ht

  • Servlet实现文件上传,可多文件上传示例

    一.Servlet实现文件上传,需要添加第三方提供的jar包 下载地址: 1) commons-fileupload-1.2.2-bin.zip:  点击打开链接 2)  commons-io-2.3-bin.zip:    点击打开链接 接着把这两个jar包放到 lib文件夹下: 二:文件上传的表单提交方式必须是POST方式, 编码类型:enctype="multipart/form-data",默认是 application/x-www-form-urlencoded 比如: &l

  • Java Servlet简单实例分享(文件上传下载demo)

    项目结构 src com servletdemo DownloadServlet.java ShowServlet.java UploadServlet.java WebContent jsp servlet download.html fileupload.jsp input.jsp WEB-INF lib commons-fileupload-1.3.1.jar commons-io-2.4.jar 1.简单实例 ShowServlet.java package com.servletdem

  • servlet+JSP+mysql实现文件上传的方法

    本文实例讲述了servlet+JSP+mysql实现文件上传的方法.分享给大家供大家参考,具体如下: 一.文件上传的基本操作: 1. 表单属性enctype的设置 multipart/form-data和application/x-www-form-urlencoded的区别 FORM元素的enctype属性指定了表单数据向服务器提交时所采用的编码类型,默认的缺省值是"application/x-www-form-urlencoded". 然而,在向服务器发送大量的文本.包含非ASCI

  • Servlet3.0实现文件上传的方法

    Servlet 实现文件上传 所谓文件上传就是将本地的文件发送到服务器中保存.例如我们向百度网盘中上传本地的资源或者我们将写好的博客上传到服务器等等就是典型的文件上传. Servlet 3.0 上次完成文件下载功能使用的是 Servlet 2.5,但是想要完成文件上传,那么继续使用 Servlet 2.5 肯定不是一个好的选择,因此我们使用 Servlet 3.0 来完成文件上传.下面我来简单介绍一下 Servlet 3.0 的新特性: 1.新增的注解支持 该版本新增了若干注解,用于简化 Ser

随机推荐