Я нашел этот пример на заказ RequestBody
.
Итак, я создаю CountingFileRequestBody
класс:
public class CountingFileRequestBody extends RequestBody {
private static final int SEGMENT_SIZE = 2048;
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);
}
}
А в основной деятельности я использую так:
RequestBody multiPartBody = new MultipartBody.Builder()
.setType(MultipartBody.FORM)
.addPart(
Headers.of("Content-Disposition", "form-data; name=\"file0\"; filename=\"" + name.split("\\.")[0] + "\""),
new CountingFileRequestBody(new File(path), mediaType, new CountingFileRequestBody.ProgressListener() {
@Override
public void transferred(long num) {
float progress = (num / (float) totalSize) * 100;
handler.post(() -> {
mProgress.setProgress((int) progress);
tvProgressPercentage.setText((int) progress + "%");
});
}
}))
.addFormDataPart("RadUAG_fileName", name)
Теперь у меня есть прогресс, который нужно показать пользователю :-)
![enter image description here](https://i.stack.imgur.com/kpXcT.png)