我正在使用改造开发Android应用程序。我想用参数将任何类型的文件上传到我的服务器。例如,在我的应用程序中有文本字段,如电子邮件和文件上载字段。当我进入字段并单击提交按钮。它显示上载文件的百分比并将文件和数据发送到服务器。当上传过程进行时,它想要显示已完成文件的百分比。怎么可能? 有没有参考网站或教程? 请帮帮我?
答案 0 :(得分:1)
创建此界面
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)));
}
};