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 相关文章推荐
精通Javascript系列之数据类型 字符串
Jun 08 Javascript
raphael.js绘制中国地图 地图绘制方法
Feb 12 Javascript
jquery live()调用不存在的解决方法
Feb 26 Javascript
微信小程序之批量上传并压缩图片的实例代码
Jul 05 Javascript
react-native动态切换tab组件的方法
Jul 07 Javascript
Layer弹出层动态获取数据的方法
Aug 20 Javascript
vue elementui form表单验证的实现
Nov 11 Javascript
inquirer.js一个用户与命令行交互的工具详解
May 18 Javascript
使用pkg打包ThinkJS项目的方法步骤
Dec 30 Javascript
Element Dialog对话框的使用示例
Jul 26 Javascript
vue实现点击出现操作弹出框的示例
Nov 05 Javascript
JavaScript实现切换多张图片
Jan 27 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隐形一句话后门,和ThinkPHP框架加密码程序(base64_decode)
2011/11/02 PHP
用Javascript评估用户输入密码的强度(Knockout版)
2011/11/30 Javascript
JS检测图片大小的实例
2013/08/21 Javascript
Nodejs+express+html5 实现拖拽上传
2014/08/08 NodeJs
实现无刷新联动例子汇总
2015/05/20 Javascript
jQuery实现本地预览上传图片功能
2016/01/08 Javascript
Bootstrap入门书籍之(四)菜单、按钮及导航
2016/02/17 Javascript
jQuery.Form实现Ajax上传文件同时设置headers的方法
2017/06/26 jQuery
写给vue新手们的vue渲染页面教程
2017/09/01 Javascript
Three.js利用dat.GUI如何简化试验流程详解
2017/09/26 Javascript
Vue2仿淘宝实现省市区三级联动
2020/04/15 Javascript
React BootStrap用户体验框架快速上手
2018/03/06 Javascript
Vue+Node实现商品列表的分页、排序、筛选,添加购物车功能详解
2019/12/07 Javascript
JavaScript对象属性操作实例解析
2020/02/04 Javascript
基于 Vue 的 Electron 项目搭建过程图文详解
2020/07/22 Javascript
基于vue 动态菜单 刷新空白问题的解决
2020/08/06 Javascript
vue开发chrome插件,实现获取界面数据和保存到数据库功能
2020/12/01 Vue.js
JavaScript实现弹出窗口效果
2020/12/09 Javascript
python用10行代码实现对黄色图片的检测功能
2015/08/10 Python
python cx_Oracle模块的安装和使用详细介绍
2017/02/13 Python
Python正则抓取新闻标题和链接的方法示例
2017/04/24 Python
python 内置函数filter
2017/06/01 Python
Python中的函数式编程:不可变的数据结构
2018/10/08 Python
在python中利用KNN实现对iris进行分类的方法
2018/12/11 Python
对python 通过ssh访问数据库的实例详解
2019/02/19 Python
使用Python paramiko模块利用多线程实现ssh并发执行操作
2019/12/05 Python
CSS3中媒体查询结合rem布局适配手机屏幕
2019/06/10 HTML / CSS
HTML5实现简单图片上传所遇到的问题及解决办法
2016/01/20 HTML / CSS
拉飞逸官网:Lafayette 148 New York
2020/07/15 全球购物
比较基础的php面试题及答案-填空题
2014/04/26 面试题
仓库规划计划书
2014/04/28 职场文书
2014财务年终工作总结
2014/12/08 职场文书
2016大学生形势与政策心得体会
2016/01/12 职场文书
Java 中的 Unsafe 魔法类的作用大全
2021/06/26 Java/Android
PyTorch中的torch.cat简单介绍
2022/03/17 Python
JS class语法糖的深入剖析
2022/07/07 Javascript