[英]How to show progress bar when uploading a file in android retrofit
我正在使用改造开发一个 android 应用程序。 我想使用参数将任何类型的文件上传到我的服务器。 例如,在我的应用程序中有文本字段,如电子邮件和文件上传字段。 当我输入字段并单击提交按钮时。 它显示上传文件的百分比并将文件和数据发送到服务器。 当上传过程进行时,它想显示已完成文件的百分比。 怎么可能? 有没有参考网站或教程? 请帮我?
创建这个接口
public interface ProgressListener {
void transferred(long num);
}
而这堂课
public class CountingTypedFile extends TypedFile {
private static final int BUFFER_SIZE = 4096;
private final ProgressListener listener;
public CountingTypedFile(String mimeType, File file, ProgressListener listener) {
super(mimeType, file);
this.listener = listener;
}
@Override
public void writeTo(OutputStream out) throws IOException {
byte[] buffer = new byte[BUFFER_SIZE];
FileInputStream in = new FileInputStream(super.file());
long total = 0;
try {
int read;
while ((read = in.read(buffer)) != -1) {
total += read;
out.write(buffer, 0, read);
try{
if (this.listener != null)
this.listener.transferred(total);
}catch (Exception e){
}
}
} finally {
in.close();
}
}
}
定义这个方法
@POST("/{path}")
public JsonObject makeRequestForAttachmentsUpload(@Path(value = "path", encode = false) String path, @Body MultipartTypedOutput multipartTypedOutput);
然后像这样调用上传方法
RestClient restClient = new RestClient();
ApiService apiService = restClient.getApiService();
MultipartTypedOutput multipartTypedOutput = new MultipartTypedOutput();
// add and string parameters
for (String key : requestParams.keySet()) {
multipartTypedOutput.addPart(key, new TypedString(requestParams.get(key)));
}
// add attchments
multipartTypedOutput.addPart(attachmentName, new CountingTypedFile(attachmentType, new File(attachmentPath), listener));
apiService.makeRequestForAttachmentsUpload(requestName, multipartTypedOutput);
并通过定义此侦听器来侦听进度
listener = new DPAPIService.ProgressListener() {
@Override
public void transferred(long num) {
publishProgress(((num / (float) fileSize)));
}
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.