public class ProgressRequestBody extends RequestBody {
private File mFile;
private String mPath;
private UploadCallbacks mListener;
private static final int DEFAULT_BUFFER_SIZE = 2048;
public interface UploadCallbacks {
void onProgressUpdate(int percentage);
void onError();
void onFinish();
}
public ProgressRequestBody(File file,UploadCallbacks listener) {
mFile = file;
mListener = listener;
}
@Override
public MediaType contentType() {
// i want to upload only images
return MediaType.parse("image/*");
}
@Override
public long contentLength() throws IOException {
return mFile.length();
}
@Override
public void writeTo(BufferedSink sink) throws IOException {
Source source = null;
try {
source = Okio.source(mFile);
long total = 0;
long read;
while ((read = source.read(sink.buffer(), DEFAULT_BUFFER_SIZE)) != -1) {
total += read;
sink.flush();
mListener.onProgressUpdate((int)(100 * total / mFile.length()));
}
} finally {
Util.closeQuietly(source);
}
}
在上面的代码中,当我们上传单个文件时,进度条会出现两次。 表示首先在内部写入文件并在第二次上传。 所以它显示了两个进度条。我们怎样才能避免第一个进度条显示?