重新学javaweb---文件上传监听--进度条

时间:2022-08-28 09:31:20

update方法API
void update(long pBytesRead, long pContentLength, int pItems)

Parameters:

pBytesRead - The total number of bytes, which have been read so far.

pContentLength - The total number of bytes, which are being read. May be -1, if this number is unknown.

pItems - The number of the field, which is currently being read. (0 = no item so far, 1 = first item is being read, …)


  • ProgressListener显示上传进度
ProgressListener progressListener = new ProgressListener() {
    public void update(long pBytesRead, long pContentLength, int pItems) {

    System.out.println("到现在为止, " + pBytesRead + " 字节已上传,总大小为 "
              + pContentLength);
    }
};
upload.setProgressListener(progressListener);
  • 以KB为单位显示上传进度
long temp = -1;   //temp注意设置为类变量
long ctemp = pBytesRead /1024; 
if (mBytes == ctemp)  
    return; 
temp = mBytes; 

但上面这个会出现小数点太多或除不尽的问题。
double是个不太精确的,只是个近似值
用BigDecimal 保存小数点,他可以表示 不可改变,任意精度的有符号十进制数
可以选择留下几位小数,可以选择什么舍入模式


            // --设置文件上传监听
            fileUpload.setProgressListener(new ProgressListener() {
                Long beginTime = System.currentTimeMillis();

                public void update(long bytesRead, long contentLength, int items) {
                    BigDecimal br = new BigDecimal(bytesRead).divide(
                            new BigDecimal(1024), 2, BigDecimal.ROUND_HALF_UP);
                    BigDecimal cl = new BigDecimal(contentLength).divide(
                            new BigDecimal(1024), 2, BigDecimal.ROUND_HALF_UP);
                    System.out.print("当前读取的是第" + items + "个上传项,总大小" + cl
                            + "KB,已经读取" + br + "KB");
                    // 剩余字节数
                    BigDecimal ll = cl.subtract(br);
                    System.out.print("剩余" + ll + "KB");
                    // 上传百分比
                    BigDecimal per = br.multiply(new BigDecimal(100)).divide(
                            cl, 2, BigDecimal.ROUND_HALF_UP);
                    System.out.print("已经完成" + per + "%");
                    // 上传用时
                    Long nowTime = System.currentTimeMillis();
                    Long useTime = (nowTime - beginTime) / 1000;
                    System.out.print("已经用时" + useTime + "秒");
                    // 上传速度
                    BigDecimal speed = new BigDecimal(0);
                    if (useTime != 0) {
                        speed = br.divide(new BigDecimal(useTime), 2,
                                BigDecimal.ROUND_HALF_UP);
                    }
                    System.out.print("上传速度为" + speed + "KB/S");
                    // 大致剩余时间
                    BigDecimal ltime = new BigDecimal(0);
                    if (!speed.equals(new BigDecimal(0))) {
                        ltime = ll.divide(speed, 0, BigDecimal.ROUND_HALF_UP);
                    }
                    System.out.print("大致剩余时间为" + ltime + "秒");

                    System.out.println();
                }

            });