我正在尝试使用okhttp3实现暂停和恢复功能以在android中上传文件。要上传的文件将转换为块然后上传每个块。当网络出现错误时,应用程序必须尝试上传剩余的从那里停下来的块。这是我一直在使用的自定义请求主体
class ProgressRequestBody extends RequestBody{
public ProgressRequestBody(final File mfile, final UploadCallbacks listener) {
this.mfile = mfile;
this.mListener = listener;
}
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 onFinished();
}
@Override
public long contentLength() throws IOException {
return mfile.length();
}
@Nullable
@Override
public MediaType contentType() {
return MediaType.parse("image/*");
}
@Override
public void writeTo(BufferedSink sink) throws IOException {
long fileLength = mfile.length();
byte[] buffer = new byte[DEFAULT_BUFFER_SIZE];
FileInputStream fileInputStream = new FileInputStream(mfile);
long uploaded = 0;
try{
int read;
Handler handler = new Handler(Looper.getMainLooper());
while((read = fileInputStream.read(buffer)) != -1)
{
handler.post(new ProgressUpdater(uploaded,fileLength));
uploaded += read;
sink.write(buffer,0,read);
}
}
finally {
fileInputStream.close();
}
}
这是用于上传功能的代码
ProgressRequestBody fileBody = new ProgressRequestBody(file,this);
MultipartBody.Part filePart = MultipartBody.Part.createFormData("datafile",file.getName(),fileBody);
apiInterface = APIClient.getClient().create(ApiInterface.class);
Call<SuccessResponse> call = apiInterface.uploadImage(filePart);
call.enqueue(new Callback<SuccessResponse>() {....}