我只是想解决一个类似的案例,但我拥有的是大量文件。
我尝试使用循环解决它:
recordsDirectory.mkdirs();
final File[] list_files = recordsDirectory.listFiles();
int cont = list_files.length;
for (int i = 0; i < cont; i++) {
final File ref_file = list_files[i];
String source_filepath = ref_file.getPath();
RequestBody requestBody =
RequestBody.create(MediaType.parse("multipart/form-data"), ref_file);
Call<DeliveryResponse> call = apiService.upload(requestBody, description);
call.enqueue(new Callback<DeliveryResponse>() {
@Override
public void onResponse(Response<DeliveryResponse> response, Retrofit retrofit) {
Log.v(TAG, "[" + TAG + "] Upload success. status: " + response.toString());
DeliveryResponse deliveryResponse = response.body();
Log.v(TAG, "response code: " + deliveryResponse.mStatus);
Log.v(TAG, "response code: " + response.code());
Log.v(TAG, "ref_file: " + ref_file.getPath());
if (response.isSuccess()) {
Log.i(TAG, "[" + TAG + "] The server has response with a status distinct to 200.");
}
else {
if (deliveryResponse.mStatus == 1) {
Log.i(TAG, "[" + TAG + "] The server has response with 1 as status.");
boolean deleted = ref_file.delete();
} else {
Log.i(TAG, "[" + TAG + "] The server has response with 0 as status.");
}
}
}
@Override
public void onFailure(Throwable t) {
Log.e("Upload", t.getMessage());
}
});
}
/***********************************************
RETROFIT API
************************************************/
public interface MyApiEndpointInterface {
@Multipart
@POST("/elderbask/api/sensors/accelerometer")
Call<DeliveryResponse> upload(
@Part("myfile\"; filename=\"image.png\" ") RequestBody file,
@Part("description") String description
);
}
public static class DeliveryResponse {
@SerializedName("status")
int mStatus;
public DeliveryResponse(int status) {
this.mStatus = status;
}
public String toString(){
return "mStatus: " + this.mStatus;
}
}
但是这个解决方案并没有我想象的那么好。我有很多超时异常,并且错误的硬编码文件名非常糟糕。