Skip to content

Instantly share code, notes, and snippets.

@douglasjunior
Created February 19, 2016 11:33
Show Gist options
  • Save douglasjunior/9bb7b7d8a92cebec2b48 to your computer and use it in GitHub Desktop.
Save douglasjunior/9bb7b7d8a92cebec2b48 to your computer and use it in GitHub Desktop.
Class used to monitoring the file upload progress in Retrofit2 library.
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import okhttp3.MediaType;
import okhttp3.RequestBody;
import okio.BufferedSink;
/**
* Class used to monitoring the file upload progress in Retrofit2 library.
* <p/>
* Created by douglas on 18/02/16.
*/
public class ProgressRequestBody extends RequestBody {
private final byte[] mBytes;
private final File mFile;
private UploadCallbacks mListener;
private final long mLenght;
private final MediaType mMediaType;
private static final int DEFAULT_BUFFER_SIZE = 1024;
public interface UploadCallbacks {
void onProgressUpdate(long uploaded, long lenght, int percentage);
}
private ProgressRequestBody(final byte[] bytes, final File file, long lenght, MediaType mediaType, UploadCallbacks listener) {
mBytes = bytes;
mFile = file;
mLenght = lenght;
mMediaType = mediaType;
mListener = listener;
}
/**
* Send byte array.
*
* @param bytes
* @param mediaType
* @param listener
*/
public ProgressRequestBody(final byte[] bytes, final MediaType mediaType, final UploadCallbacks listener) {
this(bytes, null, bytes.length, mediaType, listener);
}
/**
* Send file.
*
* @param file
* @param mediaType
* @param listener
* @throws FileNotFoundException
*/
public ProgressRequestBody(final File file, final MediaType mediaType, final UploadCallbacks listener) throws FileNotFoundException {
this(null, file, file.length(), mediaType, listener);
}
@Override
public MediaType contentType() {
return mMediaType;
}
@Override
public long contentLength() throws IOException {
return mLenght;
}
@Override
public synchronized void writeTo(BufferedSink sink) throws IOException {
InputStream is = createInputStream();
try {
byte[] buffer = new byte[DEFAULT_BUFFER_SIZE];
long uploaded = 0;
int read;
while ((read = is.read(buffer)) != -1) {
sink.write(buffer, 0, read);
uploaded += read;
mListener.onProgressUpdate(uploaded, mLenght, (int) (100f * uploaded / mLenght));
}
} finally {
closeInputStream(is);
}
}
private void closeInputStream(InputStream is) {
try {
is.close();
} catch (Exception ex) {
ex.printStackTrace();
}
}
private InputStream createInputStream() throws FileNotFoundException {
if (mBytes != null) {
return new ByteArrayInputStream(mBytes);
} else if (mFile != null) {
return new FileInputStream(mFile);
}
throw new IllegalArgumentException("File and bytes are null");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment