我们正在使用 Retrofit multi-part 进行文件上传过程。
我们希望在文件上传时暂停/恢复。
我想知道有没有可能?
多部分文件上传代码
RequestBody requestFile =
RequestBody.create(MediaType.parse("multipart/form-data"), file);
// MultipartBody.Part is used to send also the actual file name
MultipartBody.Part body =MultipartBody.Part.createFormData("image", file.getName(), requestFile);
Call<ResponseBody> call= api.uploadFile(body);
最佳答案
是的,这是可能的。您必须创建自己的请求正文。
public class PausableRequestBody extends RequestBody {
private static final int BUFFER_SIZE = 2048;
private File mFile;
private long uploadedData;
public PausableRequestBody(final File file) {
mFile = file;
}
@Override
public MediaType contentType() {
return MediaType.parse("image/*");
}
@Override
public long contentLength() throws IOException {
return mFile.length();
}
@Override
public void writeTo(BufferedSink bs) throws IOException {
long fileLength = mFile.length();
byte[] buffer = new byte[BUFFER_SIZE];
FileInputStream in = new FileInputStream(mFile);
try {
int read;
while ((read = in.read(buffer)) != -1) {
this.uploadedData += read;
bs.write(buffer, 0, read);
}
} finally {
in.close();
}
}
public long getUploadedData() {
return uploadedData;
}
}
使用附加而不是写入..
使用以下 Retrofit 调用
PausableRequestBody fileBody = new PausableRequestBody(file, this);
MultipartBody.Part filePart = MultipartBody.Part.createFormData("image", file.getName(), fileBody);
Call<JsonObject> request = RetrofitClient.uploadImage(filepart);
request.enqueue(new Callback<JsonObject>{...});
要暂停请求,您必须取消通话 请求.取消()
重新启动 使用与上述相同方法的相同 PausableRequestBody 对象
关于android - Retrofit 多部分请求是否可以暂停和恢复?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51407012/