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); 2 Answers
Answers 1
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
Answers 2
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 cancel the request request.cancel()
to restart use the same PausableRequestBody object with the same method mentioned above
0 comments:
Post a Comment