通过在Android中使用MultipartBuilder获得进度

时间:2019-04-30 04:43:08

标签: android okhttp3

我正在使用okhttp将http表单发送到server。这是我的要求:

OkHttpClient client = new OkHttpClient();     
RequestBody multiPartBody = new MultipartBody.Builder()
                        .setType(MultipartBody.FORM)
                        .addPart(
                                Headers.of("Content-Disposition", "form-data; name=\"file0\"; filename=\"" + name.split("\\.")[0] + "\""),
                                RequestBody.create(MediaType.parse(mediaType), new File(path)))
                        .addFormDataPart("RadUAG_fileName", name)
                        .addFormDataPart("RadUAG_position", "0")
    Request request = new Request.Builder()
                        .url("http://xxx.xxx.xxx.xxx/ArchiveSite/Handlers/RadUploadHandler.ashx")
                        .post(multiPartBody)
                        .build();
    client.newCall(request).execute()

现在想象一下我的文件很大,我想向用户显示向服务器发送了多少上传内容。

我如何获取发送到服务器并显示给用户进度条的文件?

您可以看到我正在使用okhttp,并且我想在此库中找到解决方案。

1 个答案:

答案 0 :(得分:0)

我找到了这个example自定义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