创建这个接口
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)));
}
};