I am trying to implement a a progress bar to indicate the progress of a multipart file upload.
I have read from a comment on this answer - https://stackoverflow.com/
RequestBody, no need to implement custom BufferedSink. We can allocate Okio buffer to read from image file, and connect this buffer to sink.For an example, please see the below createCustomRequestBody function
public static RequestBody createCustomRequestBody(final MediaType contentType, final File file) {
return new RequestBody() {
@Override public MediaType contentType() {
return contentType;
}
@Override public long contentLength() {
return file.length();
}
@Override public void writeTo(BufferedSink sink) throws IOException {
Source source = null;
try {
source = Okio.source(file);
//sink.writeAll(source);
Buffer buf = new Buffer();
Long remaining = contentLength();
for (long readCount; (readCount = source.read(buf, 2048)) != -1; ) {
sink.write(buf, readCount);
Log.d(TAG, "source size: " + contentLength() + " remaining bytes: " + (remaining -= readCount));
}
} catch (Exception e) {
e.printStackTrace();
}
}
};
}
to use -
.addPart(
Headers.of("Content-Disposition", "form-data; name=\"image\""),
createCustomRequestBody(MediaType.parse("image/png"), new File("test.jpg")))
.build()