As far as I can see in this post, no updates regarding the image upload progress response has been made and you still have to override the
writeTo method as shown in this SO answer by making a ProgressListener interface and using a sub-class of TypedFile to override the writeTo method.
So, there isn't any built-in way to show progress when using retrofit 2 library.
/* JsonObject above can be replace with you own model, just want to
make this notable. */
Now you can get progress of your upload.
In your activity (or fragment):
class MyActivity extends AppCompatActivity implements ProgressRequestBody.UploadCallbacks {
ProgressBar progressBar;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
progressBar = findViewById(R.id.progressBar);
ProgressRequestBody fileBody = new ProgressRequestBody(file, this);
MultipartBody.Part filePart =
MultipartBody.Part.createFormData("image", file.getName(), fileBody);
Call<JsonObject> request = RetrofitClient.uploadImage(filepart);
request.enqueue(new Callback<JsonObject>() {
@Override
public void onResponse(Call<JsonObject> call, Response<JsonObject> response) {
if(response.isSuccessful()){
/* Here we can equally assume the file has been downloaded successfully because for some reasons the onFinish method might not be called, I have tested it myself and it really not consistent, but the onProgressUpdate is efficient and we can use that to update our progress on the UIThread, and we can then set our progress to 100% right here because the file already downloaded finish. */
}
}
@Override
public void onFailure(Call<JsonObject> call, Throwable t) {
/* we can also stop our progress update here, although I have not check if the onError is being called when the file could not be downloaded, so I will just use this as a backup plan just in case the onError did not get called. So I can stop the progress right here. */
}
});
}
@Override
public void onProgressUpdate(int percentage) {
// set current progress
progressBar.setProgress(percentage);
}
@Override
public void onError() {
// do something on error
}
@Override
public void onFinish() {
// do something on upload finished,
// for example, start next uploading at a queue
progressBar.setProgress(100);
}
}
Here's how to handle upload file progress with a simple POST rather than Multipart. For multipart check out @Yariy's solution. Additionally, this solution uses Content URI's instead of direct file references.
public class ProgressRequestBody extends RequestBody {
private static final String LOG_TAG = ProgressRequestBody.class.getSimpleName();
public interface ProgressCallback {
public void onProgress(long progress, long total);
}
public static class UploadInfo {
//Content uri for the file
public Uri contentUri;
// File size in bytes
public long contentLength;
}
private WeakReference<Context> mContextRef;
private UploadInfo mUploadInfo;
private ProgressCallback mListener;
private static final int UPLOAD_PROGRESS_BUFFER_SIZE = 8192;
public ProgressRequestBody(Context context, UploadInfo uploadInfo, ProgressCallback listener) {
mContextRef = new WeakReference<>(context);
mUploadInfo = uploadInfo;
mListener = listener;
}
@Override
public MediaType contentType() {
// NOTE: We are posting the upload as binary data so we don't need the true mimeType
return MediaType.parse("application/octet-stream");
}
@Override
public void writeTo(BufferedSink sink) throws IOException {
long fileLength = mUploadInfo.contentLength;
byte[] buffer = new byte[UPLOAD_PROGRESS_BUFFER_SIZE];
InputStream in = in();
long uploaded = 0;
try {
int read;
while ((read = in.read(buffer)) != -1) {
mListener.onProgress(uploaded, fileLength);
uploaded += read;
sink.write(buffer, 0, read);
}
} finally {
in.close();
}
}
/**
* WARNING: You must override this function and return the file size or you will get errors
*/
@Override
public long contentLength() throws IOException {
return mUploadInfo.contentLength;
}
private InputStream in() throws IOException {
InputStream stream = null;
try {
stream = getContentResolver().openInputStream(mUploadInfo.contentUri);
} catch (Exception ex) {
Log.e(LOG_TAG, "Error getting input stream for upload", ex);
}
return stream;
}
private ContentResolver getContentResolver() {
if (mContextRef.get() != null) {
return mContextRef.get().getContentResolver();
}
return null;
}
}
To initiate the upload:
// Create a ProgressRequestBody for the file
ProgressRequestBody requestBody = new ProgressRequestBody(
getContext(),
new UploadInfo(myUri, fileSize),
new ProgressRequestBody.ProgressCallback() {
public void onProgress(long progress, long total) {
//Update your progress UI here
//You'll probably want to use a handler to run on UI thread
}
}
);
// Upload
mRestClient.uploadFile(requestBody);
Warning, if you forget to override the contentLength() function you may receive a few obscure errors:
Modified Yuriy Kolbasinskiy's to use rxjava and use kotlin.
Added a workaround for using HttpLoggingInterceptor at the same time
class ProgressRequestBody : RequestBody {
val mFile: File
val ignoreFirstNumberOfWriteToCalls : Int
constructor(mFile: File) : super(){
this.mFile = mFile
ignoreFirstNumberOfWriteToCalls = 0
}
constructor(mFile: File, ignoreFirstNumberOfWriteToCalls : Int) : super(){
this.mFile = mFile
this.ignoreFirstNumberOfWriteToCalls = ignoreFirstNumberOfWriteToCalls
}
var numWriteToCalls = 0
protected val getProgressSubject: PublishSubject<Float> = PublishSubject.create<Float>()
fun getProgressSubject(): Observable<Float> {
return getProgressSubject
}
override fun contentType(): MediaType {
return MediaType.parse("video/mp4")
}
@Throws(IOException::class)
override fun contentLength(): Long {
return mFile.length()
}
@Throws(IOException::class)
override fun writeTo(sink: BufferedSink) {
numWriteToCalls++
val fileLength = mFile.length()
val buffer = ByteArray(DEFAULT_BUFFER_SIZE)
val `in` = FileInputStream(mFile)
var uploaded: Long = 0
try {
var read: Int
var lastProgressPercentUpdate = 0.0f
read = `in`.read(buffer)
while (read != -1) {
uploaded += read.toLong()
sink.write(buffer, 0, read)
read = `in`.read(buffer)
// when using HttpLoggingInterceptor it calls writeTo and passes data into a local buffer just for logging purposes.
// the second call to write to is the progress we actually want to track
if (numWriteToCalls > ignoreFirstNumberOfWriteToCalls ) {
val progress = (uploaded.toFloat() / fileLength.toFloat()) * 100f
//prevent publishing too many updates, which slows upload, by checking if the upload has progressed by at least 1 percent
if (progress - lastProgressPercentUpdate > 1 || progress == 100f) {
// publish progress
getProgressSubject.onNext(progress)
lastProgressPercentUpdate = progress
}
}
}
} finally {
`in`.close()
}
}
companion object {
private val DEFAULT_BUFFER_SIZE = 2048
}
}
An example video upload interface
public interface Api {
@Multipart
@POST("/upload")
Observable<ResponseBody> uploadVideo(@Body MultipartBody requestBody);
}
An example function to post a video:
fun postVideo(){
val api : Api = Retrofit.Builder()
.client(OkHttpClient.Builder()
//.addInterceptor(HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.BODY))
.build())
.baseUrl("BASE_URL")
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.build()
.create(Api::class.java)
val videoPart = ProgressRequestBody(File(VIDEO_URI))
//val videoPart = ProgressRequestBody(File(VIDEO_URI), 1) //HttpLoggingInterceptor workaround
val requestBody = MultipartBody.Builder()
.setType(MultipartBody.FORM)
.addFormDataPart("example[name]", place.providerId)
.addFormDataPart("example[video]","video.mp4", videoPart)
.build()
videoPart.getProgressSubject()
.subscribeOn(Schedulers.io())
.subscribe { percentage ->
Log.i("PROGRESS", "${percentage}%")
}
var postSub : Disposable?= null
postSub = api.postVideo(requestBody)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe({ r ->
},{e->
e.printStackTrace()
postSub?.dispose();
}, {
Toast.makeText(this,"Upload SUCCESS!!",Toast.LENGTH_LONG).show()
postSub?.dispose();
})
}
@luca992 Thank you for your answer. I have implemented this in JAVA and now it is working fine.
public class ProgressRequestBodyObservable extends RequestBody {
File file;
int ignoreFirstNumberOfWriteToCalls;
int numWriteToCalls;`enter code here`
public ProgressRequestBodyObservable(File file) {
this.file = file;
ignoreFirstNumberOfWriteToCalls =0;
}
public ProgressRequestBodyObservable(File file, int ignoreFirstNumberOfWriteToCalls) {
this.file = file;
this.ignoreFirstNumberOfWriteToCalls = ignoreFirstNumberOfWriteToCalls;
}
PublishSubject<Float> floatPublishSubject = PublishSubject.create();
public Observable<Float> getProgressSubject(){
return floatPublishSubject;
}
@Override
public MediaType contentType() {
return MediaType.parse("image/*");
}
@Override
public long contentLength() throws IOException {
return file.length();
}
@Override
public void writeTo(BufferedSink sink) throws IOException {
numWriteToCalls++;
float fileLength = file.length();
byte[] buffer = new byte[2048];
FileInputStream in = new FileInputStream(file);
float uploaded = 0;
try {
int read;
read = in.read(buffer);
float lastProgressPercentUpdate = 0;
while (read != -1) {
uploaded += read;
sink.write(buffer, 0, read);
read = in.read(buffer);
// when using HttpLoggingInterceptor it calls writeTo and passes data into a local buffer just for logging purposes.
// the second call to write to is the progress we actually want to track
if (numWriteToCalls > ignoreFirstNumberOfWriteToCalls ) {
float progress = (uploaded / fileLength) * 100;
//prevent publishing too many updates, which slows upload, by checking if the upload has progressed by at least 1 percent
if (progress - lastProgressPercentUpdate > 1 || progress == 100f) {
// publish progress
floatPublishSubject.onNext(progress);
lastProgressPercentUpdate = progress;
}
}
}
} finally {
in.close();
}
}
}
I realize this question was answered years ago, but I thought I'd update it for Kotlin:
Create a class that extends RequestBody. Be sure to populate the ContentType enum class to use whichever content types you need to support.
class RequestBodyWithProgress(
private val file: File,
private val contentType: ContentType,
private val progressCallback:((progress: Float)->Unit)?
) : RequestBody() {
override fun contentType(): MediaType? = MediaType.parse(contentType.description)
override fun contentLength(): Long = file.length()
override fun writeTo(sink: BufferedSink) {
val fileLength = contentLength()
val buffer = ByteArray(DEFAULT_BUFFER_SIZE)
val inSt = FileInputStream(file)
var uploaded = 0L
inSt.use {
var read: Int = inSt.read(buffer)
val handler = Handler(Looper.getMainLooper())
while (read != -1) {
progressCallback?.let {
uploaded += read
val progress = (uploaded.toDouble() / fileLength.toDouble()).toFloat()
handler.post { it(progress) }
sink.write(buffer, 0, read)
}
read = inSt.read(buffer)
}
}
}
enum class ContentType(val description: String) {
PNG_IMAGE("image/png"),
JPG_IMAGE("image/jpg"),
IMAGE("image/*")
}
}
Upload the file using Retrofit:
fun uploadFile(fileUri: Uri, progressCallback:((progress: Float)->Unit)?) {
val file = File(fileUri.path)
if (!file.exists()) throw FileNotFoundException(fileUri.path)
// create RequestBody instance from file
val requestFile = RequestBodyWithProgress(file, RequestBodyWithProgress.ContentType.PNG_IMAGE, progressCallback)
// MultipartBody.Part is used to send also the actual file name
val body = MultipartBody.Part.createFormData("image_file", file.name, requestFile)
publicApiService().uploadFile(body).enqueue(object : Callback<MyResponseObj> {
override fun onFailure(call: Call<MyResponseObj>, t: Throwable) {
}
override fun onResponse(call: Call<MyResponseObj>, response: Response<MyResponseObj>) {
}
})
}
I appericiate @Yuriy Kolbasinskiy given answer but it gives error for me
"expected 3037038 bytes but received 3039232" after I Change some on WriteTo() function. The Answer is in Kotlin which given below :-
override fun writeTo(sink: BufferedSink) {
var uploaded:Long = 0
var source: Source? = null
try {
source = Okio.source(file)
val handler = Handler(Looper.getMainLooper())
do {
val read = source.read(sink.buffer(), 2048)
while (read == -1L) return
uploaded += read
handler.post(ProgressUpdater(uploaded, file.length()))
sink.flush()
} while(true)
} finally {
Util.closeQuietly(source)
}
}
Here is an extension function heavily inspired from this thread and it is working really well.
fun File.toRequestBody(progressCallback: ((progress: Int) -> Unit)?): RequestBody {
return object : RequestBody() {
private var currentProgress = 0
private var uploaded = 0L
override fun contentType(): MediaType? {
val fileType = name.substringAfterLast('.', "")
return fileType.toMediaTypeOrNull()
}
@Throws(IOException::class)
override fun writeTo(sink: BufferedSink) {
source().use { source ->
do {
val read = source.read(sink.buffer, 2048)
if (read == -1L) return // exit at EOF
sink.flush()
uploaded += read
/**
* The value of newProgress is going to be in between 0.0 - 2.0
*/
var newProgress = ((uploaded.toDouble() / length().toDouble()))
/**
* To map it between 0.0 - 100.0
* Need to multiply it with 50
* (OutputMaxRange/InputMaxRange)
* 100 / 2 = 50
*/
newProgress = (50 * newProgress)
if (newProgress.toInt() != currentProgress) {
progressCallback?.invoke(newProgress.toInt())
}
currentProgress = newProgress.toInt()
} while (true)
}
}
}
}