HttpClient的文件上传进度

package cn.police.bz.util;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import org.apache.http.entity.mime.content.FileBody;

import android.util.Log;

/**
 * 能够显示进度的FileBody
 * 
 * @author Mr_wu
 */
public class FileBodySomeProgress extends FileBody {
    private static final boolean debug = true;
    private static final String TAG = "FileBodySomeProgress";

    /**
     * 更新进度接口
     * 
     * @author Mr_wu
     */
    public static interface UpdateProgress {
        /**
         * 更新进度
         * 
         * @param progress
         *            当前完成了多少字节
         */
        public void update(long contentLength, long progress);

        /**
         * 上传多少字节更新一次进度
         * 
         * @return
         */
        public int getBlockSize();
    }

    /** 进度更新器 */
    private UpdateProgress up;

    public FileBodySomeProgress(File file, UpdateProgress up) {
        super(file);
        if (up != null) {
            this.up = up;
        } else {
            this.up = new UpdateProgress() {
                @Override
                public int getBlockSize() {
                    return 1024 * 8;
                }

                @Override
                public void update(long contentLength, long progress) {
                    if (debug) {
                        Log.d(TAG, (int) (((float) progress / contentLength) * 100) + "%");
                    }
                }
            };
        }
    }

    @Override
    public void writeTo(OutputStream out) throws IOException {
        // 文件输入流
        final InputStream in = super.getInputStream();
        try {
            // 缓存
            final byte[] tmp = new byte[up.getBlockSize()];
            // 内容长度
            final long contentLength = getContentLength();
            // 用来记录进度
            long progress = 0;
            for (int len = 0; (len = in.read(tmp)) != -1; up.update(contentLength, progress)) {
                out.write(tmp, 0, len);
                progress += len;
            }
            out.flush();
        } finally {
            in.close();
        }
    }

    @Override
    public void writeTo(OutputStream out, int mode) throws IOException {
        this.writeTo(out);
    }
}

 上面这个是实现单个文件上传进度管理;

转载于:https://www.cnblogs.com/moqi2013/p/3481567.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值