Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible pause & resume for Retrofit multipart request?

We are using Retrofit multi-part for file uploading process.

We want pause/resume when file uploading.

I want to know its possible or not?

Code for multi-part file upload

  RequestBody requestFile =
            RequestBody.create(MediaType.parse("multipart/form-data"), file);

  // MultipartBody.Part is used to send also the actual file name
  MultipartBody.Part body =MultipartBody.Part.createFormData("image", file.getName(), requestFile);
  Call<ResponseBody> call= api.uploadFile(body);
like image 262
Ranjithkumar Avatar asked Jul 18 '18 16:07

Ranjithkumar


2 Answers

Yes its possible. You would have to create your own request body.

   public class PausableRequestBody extends RequestBody {
    private static final int BUFFER_SIZE = 2048;
    private File mFile;
    private long uploadedData;

    public PausableRequestBody(final File file) {
        mFile = file;
    }

    @Override
    public MediaType contentType() {
        return MediaType.parse("image/*");
    }

    @Override
    public long contentLength() throws IOException {
        return mFile.length();
    }

    @Override
    public void writeTo(BufferedSink bs) throws IOException {
        long fileLength = mFile.length();
        byte[] buffer = new byte[BUFFER_SIZE];
        FileInputStream in = new FileInputStream(mFile);

        try {
            int read;
            while ((read = in.read(buffer)) != -1) {
                this.uploadedData += read;
                bs.write(buffer, 0, read);
            }
        } finally {
            in.close();
        }
    }

    public long getUploadedData() {
        return uploadedData;
    }
}

use append instead of write..

Use following Retrofit call

PausableRequestBody fileBody = new PausableRequestBody(file, this);
        MultipartBody.Part filePart = MultipartBody.Part.createFormData("image", file.getName(), fileBody);

        Call<JsonObject> request = RetrofitClient.uploadImage(filepart);
        request.enqueue(new Callback<JsonObject>{...});

to pause the request you would have to cancel the call request.cancel()

to restart use the same PausableRequestBody object with the same method mentioned above

like image 178
aanshu Avatar answered Sep 25 '22 04:09

aanshu


As suggested by Jake Wharton from Square,

There is no built-in pause or resume for retrofit.

If you want to stick on to retrofit then you may need to make your backend to support range requests. This can help you to break the connection at any time during a streaming download. You can then use the range headers in every subsequent requests to support pause or resume download.

You may also check this answer using using okhttp

like image 41
Navneet Krishna Avatar answered Sep 25 '22 04:09

Navneet Krishna