-
-
Save douglarek/43c320592b9acc4c9224db0e3d4cb6b9 to your computer and use it in GitHub Desktop.
Uploading a file with a progress displayed using OkHttp
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| package com.appsrise.bildkontakte.data; | |
| import com.squareup.okhttp.MediaType; | |
| import com.squareup.okhttp.RequestBody; | |
| import com.squareup.okhttp.internal.Util; | |
| import java.io.File; | |
| import java.io.IOException; | |
| import okio.BufferedSink; | |
| import okio.Okio; | |
| import okio.Source; | |
| 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; | |
| } | |
| @Override | |
| public long contentLength() { | |
| return file.length(); | |
| } | |
| @Override | |
| public MediaType contentType() { | |
| return MediaType.parse(contentType); | |
| } | |
| @Override | |
| public void writeTo(BufferedSink sink) throws IOException { | |
| Source source = null; | |
| try { | |
| source = Okio.source(file); | |
| long total = 0; | |
| long read; | |
| while ((read = source.read(sink.buffer(), SEGMENT_SIZE)) != -1) { | |
| total += read; | |
| sink.flush(); | |
| this.listener.transferred(total); | |
| } | |
| } finally { | |
| Util.closeQuietly(source); | |
| } | |
| } | |
| public interface ProgressListener { | |
| void transferred(long num); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment