Tracking progress of multipart file upload using OKHTTP

You have to create a custom RequestBody and override writeTo method, and there you have to send your files down the sink in segments. It is very important that you flush the sink after each segment, otherwise your progress bar will fill up quickly without the file being actually sent over the network, because the contents will stay in the sink (which acts like a buffer).

public class CountingFileRequestBody extends RequestBody {

    private static final int SEGMENT_SIZE = 2048; // okio.Segment.SIZE

    private final File file;
    private final ProgressListener listener;
    private final String contentType;

    public CountingFileRequestBody(File file, String contentType, ProgressListener listener) {
        this.file = file;
        this.contentType = contentType;
        this.listener = listener;

    public long contentLength() {
        return file.length();

    public MediaType contentType() {
        return MediaType.parse(contentType);

    public void writeTo(BufferedSink sink) throws IOException {
        Source source = null;
        try {
            source = Okio.source(file);
            long total = 0;
            long read;

            while ((read =, SEGMENT_SIZE)) != -1) {
                total += read;

        } finally {

    public interface ProgressListener {
        void transferred(long num);


You can find a complete implementation that supports displaying progress in an AdapterView and also cancelling uploads at my gist:

Leave a Comment