In my application i have used Retrofit for uploading files to server. Now i want to show the percentage of file upload in progress bar. I have found a solution from this link.
But the progress bar fills quickly for every different sized files. I think this progress is not the actual amount of data uploaded to server. Is there any other solution in Retrofit for this issue..? I have also checked with this.
Is it possible in Retrofit..?
Please see my code
this is custom typed file
public class CountingTypedFile extends TypedFile {
private static final int BUFFER_SIZE = 4096;
private final ProgressListener listener;
public CountingTypedFile(String mimeType, File file, ProgressListener listener) {
super(mimeType, file);
this.listener = listener;
}
@Override
public void writeTo(OutputStream out) throws IOException {
byte[] buffer = new byte[BUFFER_SIZE];
FileInputStream in = new FileInputStream(super.file());
long total = 0;
try {
int read;
while ((read = in.read(buffer)) != -1) {
total += read;
out.flush();
this.listener.transferred(total);
out.write(buffer, 0, read);
}
} finally {
in.close();
}
}
}
This is my code part executed in doingbackground of AsyncTask
Uri myUri = Uri.parse(mImgUri);
File file = new File(AppUtils.getRealPathFromURI(context, myUri));
totalSize = file.length();
RestAdapter restAdapter = new RestAdapter.Builder()
.setEndpoint(Constants.BASE_URL)
.setLogLevel(RestAdapter.LogLevel.BASIC)
.setClient(new OkClient(new OkHttpClient()))
.build();
RetrofitCommonService mRetrofitCommonService = restAdapter.create(RetrofitCommonService.class);
Log.d("TAG", "File is not null when converting from bitmap");
TypedFile fileToSend = new CountingTypedFile("image/png", file, new ProgressListener() {
@Override
public void transferred(long num) {
publishProgress((int) ((num / (float) totalSize) * 100));
}
});
ImageUploadResponse imageUploadResponse = mRetrofitCommonService.upLoadImage(new AppUtils(context).getPhone(),
AppUtils.getDeviceId(context), fileToSend);
This is my Retrofit service
@Multipart
@POST("/user/asset")
@Headers("Accept:application/json")
ImageUploadResponse upLoadImage(@Header("mobile-number") String mPhone, @Header("uid") String imei,
@Part("file") TypedFile mBody);