代码改变世界

HttpClient的文件上传进度

2013-12-19 10:03  默契.  阅读(1412)  评论(0编辑  收藏  举报
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);
    }
}

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