[进度条]文件下载

实现思路:

  1. 首先前台搭建好下载页面,绘制一个进度条
  2. 后台写好文件下载功能
  3. 在前台中使用一个隐藏的表单,用来执行下载功能,用JS提交表单实现下载,这样执行下载时不会跳转页面
  4. 在后台实现文件下载时检测文件下载进度,同时用进度工具类来存储下载进度
  5. 在Controller中定义一个进度工具类全局引用变量,但不需要初始化,当用户进行下载时初始化进度工具类全局引用变量,已达到一个用户下载对用一个进度
  6. 前台写入Ajax事件,用JS的定时函数,来调用Ajax事件,一秒访问一次后台的进度工具类的全局引用变量,用来获取下载进度
  7. 当Ajax获取的下载进度为100%时,调用JS的停止定时函数,结束前台文件下载进度的检测
  8. 文件下载结束

JS中用到的两个函数:

  1. setInterval(function,time);第一个参数为要执行的方法,第二个参数为每隔多少时间执行一次,此函数有返回值,当调用停止定时函数时,需要传入此setInterval()方法的返回值,来结束此函数
    例如:var int = setInterval(…. , …);

  2. clearInterval(obj);方法参数为setInterval()方法的返回值,用来结束定时函数
    例如:var int = setInterval(…. , …);
    clearInterval(int);

下面为下载代码示例:

进度条工具类ProgressBarThread:

public class ProgressBarThread implements Runnable{
   

    private ArrayList<Integer> proList = new ArrayList<Integer>();
    private int progress;//当前进度
    private int totalSize;//总大小
    private boolean run = true;
    private java.text.DecimalFormat df =
                new java.text.DecimalFormat("#.00");//格式化数字 
    //进度(百分比)
    private String sum ; 
    public ProgressBarThread(int totalSize){
        this.totalSize = totalSize;
        //创建进度条
    }
    //获取总进度(百分比)
    public String total(){
        return sum;
    }

    /**
     * @param progress 进度
     */
    public void updateProgress(int progress){
        synchronized (this.proList) {
            if(this.run){
                this.proList.add(progress);
                this.proList.notify();
            }
        }
    }

    public void finish(){
        this.run = false;
        //关闭进度条
    }

    @Override
    public void run() {
        synchronized (this.proList) {
            try {
                while (this.run) {
                    if(this.proList.size()==0){
                        this.proList.wait();
                    }
                    synchronized (proList) {
                        this.progress += this.proList.remove(0);
                        //更新进度条
                        sum = df.format((int)(((float)this.progre
  • 1
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值