在Fragment B中,我有一个提交按钮,用于向服务器提交图像。单击提交按钮时,它将返回到片段A.我使用Multipart
将图像上载到服务器,并且该过程在Thread
上运行,因此用户可以在等待图像上载时执行其他任务。
片段B(单击提交按钮时)
inner class SimpleThread() :Thread() {
override fun run() {
for (i in newList!!) {
val service = RetrofitFactory.makeRetrofitService()
GlobalScope.launch(Dispatchers.IO) {
val request2 = WebApi.createImage(
activity,File(i)
)
}
}
}
的WebAPI
suspend fun createImage(
file: File?
): WebApiResponse.Image? {
val image = file?.let {
MultipartBody.Part.createFormData(
"image",
it.getName(),
RequestBody.create(MediaType.parse("image/*"), it)
)
}
return RetrofitFactory.apiCall(context) {
RetrofitFactory.makeRetrofitService().submitImages(
image
)
}
}
RetrofitService
@Multipart
@POST("create_image")
fun submitImages(
@Part image: MultipartBody.Part?
): Deferred<Response<WebApiResponse.Image>>
我可以将图像上传到服务器,但是如何在片段A上显示上传图像进度?
任何帮助表示赞赏。
所以经过一些研究后我发现了两种方法
1-如果您使用RxJava
我建议您按照此链接中的说明和注意事项display progress of multipart with retrofit using RxJava
2-如果你没有使用RxJava
将ProgressResponseBody
添加到改造构建器中,看起来像这样:
public class ProgressRequestBody extends RequestBody {
private File mFile;
private String mPath;
private UploadCallbacks mListener;
private String content_type;
private static final int DEFAULT_BUFFER_SIZE = 2048;
public interface UploadCallbacks {
void onProgressUpdate(int percentage);
void onError();
void onFinish();
}
对于这个你应该使用this answer
我猜您可以使用WorkManaget或IntenService来显示进度。 A sample to send via retrofit2您可以在服务中启动该流程。该服务可以发送新事件。
自定义RequestBody
public class FileProgressRequestBody extends RequestBody {
public interface ProgressListener {
void transferred(int size);
}
private RequestBody mRequestBody;
protected ProgressListener listener;
public FileProgressRequestBody(File file, String contentType, ProgressListener listener) {
this.mRequestBody = RequestBody.create(MediaType.parse(contentType), file);
this.listener = listener;
}
@Override
public long contentLength() throws IOException{
return mRequestBody.contentLength();
}
@Override
public MediaType contentType() {
return mRequestBody.contentType();
}
@Override
public void writeTo(@NonNull BufferedSink sink) throws IOException {
if (sink instanceof Buffer) {
// Log Interceptor
mRequestBody.writeTo(sink);
return;
}
CountingSink countingSink = new CountingSink(sink);
BufferedSink bufferedSink = Okio.buffer(countingSink);
mRequestBody.writeTo(bufferedSink);
bufferedSink.flush();
}
protected final class CountingSink extends ForwardingSink {
private long bytesWritten = 0;
public CountingSink(Sink delegate) {
super(delegate);
}
@Override
public void write(@NonNull Buffer source, long byteCount) throws IOException {
super.write(source, byteCount);
bytesWritten += byteCount;
if (listener != null) {
long length = contentLength();
if (length != 0) {
listener.transferred(MathUtils.clamp((int) (bytesWritten * 100 / length), 0, 100));
}
}
}
}
}
使用MultipartBody.Part.createFormData("image", file.getName(), new FileProgressRequestBody(file, "image/*", youListener));