我们正在使用翻新部分进行文件上传。
我们要在文件上传时暂停/继续。
我想知道它的可能性吗?
用于上传多部分文件的代码
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);
答案 0 :(得分:6)
是可能的。您将必须创建自己的请求正文。
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;
}
}
使用添加而不是写入。
使用以下改造呼叫
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>{...});
要暂停请求,您必须取消通话 request.cancel()
重新启动 使用相同的PausableRequestBody对象和上述相同的方法
答案 1 :(得分:2)
根据Jake Wharton from Square的建议,
没有内置的暂停或继续进行翻新的功能。
如果您想继续进行改造,则可能需要使后端支持range requests
。这可以帮助您在流式下载期间随时断开连接。然后,您可以在随后的每个请求中使用范围标头来支持pause or resume download
。
您也可以使用using okhttp
查看此答案