互联网技术 · 2024年2月28日

Java实现动态文件上传进度条的方法

本文实例实现文件上传的进度显示,我们先看看都有哪些问题我们要解决。

1 上传数据的处理进度跟踪

2 进度数据在用户页面的显示

就这么2个问题,

第一个问题,主要是组件的选择

必须支持数据处理侦听或通知的组件。当然,我肯定只用我自己的组件啦。基本原理是

1 使用request.getContentLength() 读取到处理数据的总长度,注意这个长度不等于文件的长度,因为Base64等编码会增加数据量,如果超过了允许的长度,直接返回-1;

2 在每读取一部分数据时(比如一行,或者64K,或者你自定义的字节数),将读取的字节数通知我们的进度跟踪程序。我取名为 UploadListener代码如下

/*
* 处理附件上传的通知。

* 各位可以继承这个类,来实现自己的特殊处理。
*
* @author 赵学庆

 public class UploadListener … {
 // 调试模式将在控制台打印出一些数据
 private boolean debug;

 // 总数据字节数
 private int total;

 // 当前已经处理的数据字节数
 private int totalCurrent = 0 ;

 // 延迟,用来调试用,免得速度太快,根本卡看不到进度
 private int delay = 0 ;

 /** */ /**
 * 处理数据通知的方法。

 * 保存已经处理的数据。并且在一定的比例进行延迟。默认每1%

 * 如果不需用延迟,可以删掉内部的代码,加快速度。
 *
 * @param size 增加的字节数
 */
 public void increaseTotalCurrent( long size) … {
 this .totalCurrent += size;
 try … {
 currentRate = totalCurrent * 100 / total;
  if (currentRate > lastRate) … {
  if (delay > 0 ) … {
  Thread.sleep(delay);
  }
  if (debug) … {
  System.out.println( ” rate= ” + totalCurrent + ” / ” + total + ” / ” + (totalCurrent * 100 / total));
  }
  lastRate = currentRate;
 }
 } catch (Exception e) … {
 e.printStackTrace();
 }
 }

 /** */ /**
 * 读取全部自己数
 *
 * @return
 */
 public int getTotal() … {
 return total;
 }

 /** */ /**
 * 读取已经处理的字节数
 *
 * @return
 */
 public int getTotalCurrent() … {
 return totalCurrent;
 }

 private long lastRate = 0 ;

 private long currentRate = 0 ;

 public int getDelay() … {
 return delay;
 }

 public void setDelay( int delay) … {
 this .delay = delay;
 }

 public void setTotal( int total) … {
 this .total = total;
 }

 public boolean isDebug() … {
 return debug;
 }

 public void setDebug( boolean debug) … {
 this .debug = debug;
 }
}

你学会了吗?

OpenMagic API

Need more than content? Move into the product flow.

If you are here for model access, pricing, developer docs, or the future API console, the dedicated product path now lives on api.openmagic.ai.