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


Posted in Javascript onJanuary 25, 2017

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

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

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

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

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

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

接收文件上传的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

效果:

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

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

代码下载:demo

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

Javascript 相关文章推荐
js null,undefined,字符串小结
Aug 21 Javascript
在JS中最常看到切最容易迷惑的语法(转)
Oct 29 Javascript
A标签中通过href和onclick传递的this对象实现思路
Apr 19 Javascript
js特效,页面下雪的小例子
Jun 17 Javascript
基于jquery的文章中所有图片width大小批量设置方法
Aug 01 Javascript
tangram框架响应式加载图片方法
Nov 21 Javascript
原生Ajax 和jQuery Ajax的区别示例分析
Dec 17 Javascript
javascript学习指南之回调问题
Apr 23 Javascript
vue里面v-bind和Props 利用props绑定动态数据的方法
Aug 27 Javascript
JS实现的input选择图片本地预览功能示例
Aug 29 Javascript
微信小程序使用wxParse解析html的方法示例
Jan 17 Javascript
js实现时钟定时器
Mar 26 Javascript
json数据处理及数据绑定
Jan 25 #Javascript
详解jQuery中ajax.load()方法
Jan 25 #Javascript
js实现鼠标左右移动,图片也跟着移动效果
Jan 25 #Javascript
JavaScript 网页中实现一个计算当年还剩多少时间的倒数计时程序
Jan 25 #Javascript
js实现文字选中分享功能
Jan 25 #Javascript
利用Js+Css实现折纸动态导航效果实例源码
Jan 25 #Javascript
jquery实现拖动效果(代码分享)
Jan 25 #Javascript
You might like
PHP Warning: Module 'modulename' already loaded in问题解决办法
2015/03/16 PHP
PHP测试成功的邮件发送案例
2015/10/26 PHP
php命令行写shell实例详解
2018/07/19 PHP
精通JavaScript 纠正 cleanWhitespace函数
2010/03/11 Javascript
juqery 学习之三 选择器 子元素与表单
2010/11/25 Javascript
extjs中grid中嵌入动态combobox的应用
2011/01/01 Javascript
Jquery多选下拉列表插件jquery multiselect功能介绍及使用
2013/05/24 Javascript
javascript禁用键盘功能键让右击及其他键无效
2013/10/09 Javascript
jQuery 常见小例汇总
2016/12/14 Javascript
Three.js基础学习之场景对象
2017/09/27 Javascript
Vue开发中遇到的跨域问题及解决方法
2020/02/11 Javascript
Vue生命周期activated之返回上一页不重新请求数据操作
2020/07/26 Javascript
浏览器JavaScript调试功能无法使用解决方案
2020/09/18 Javascript
解决vuex改变了state的值,但是页面没有更新的问题
2020/11/12 Javascript
在vue中使用inheritAttrs实现组件的扩展性介绍
2020/12/07 Vue.js
Python基本数据类型详细介绍
2014/03/11 Python
Python 出现错误TypeError: ‘NoneType’ object is not iterable解决办法
2017/01/12 Python
快速查询Python文档方法分享
2017/12/27 Python
numpy使用技巧之数组过滤实例代码
2018/02/03 Python
python如何读写json数据
2018/03/21 Python
Python 16进制与中文相互转换的实现方法
2018/07/09 Python
python实现三维拟合的方法
2018/12/29 Python
Python编写通讯录通过数据库存储实现模糊查询功能
2019/07/18 Python
python add_argument()用法解析
2020/01/29 Python
Matplotlib配色之Colormap详解
2021/01/05 Python
pytorch中index_select()的用法详解
2021/01/06 Python
h5实现获取用户地理定位的实例代码
2017/07/17 HTML / CSS
Conforama瑞士:家具、厨房、电器、装饰
2020/09/06 全球购物
Expedia瑞典官网:预订度假屋、酒店、汽车租赁、机票等
2021/01/23 全球购物
兰兰过桥教学反思
2014/02/08 职场文书
求职自我推荐信
2014/06/25 职场文书
房屋鉴定委托书范本
2014/09/23 职场文书
四风对照检查剖析材料
2014/10/07 职场文书
辞职信模板(中英文版)
2015/02/27 职场文书
庆元旦主持词
2015/07/06 职场文书
HTML5基础学习之文本标签控制
2022/03/25 HTML / CSS