I am trying out Retrofit POST using instructions provided here. The post recommends using and very old file picker as follows.
//https://github.com/iPaulPro/aFileChooser/blob/master/aFileChooser/src/com/ipaulpro/afilechooser/utils/FileUtils.java
// use the FileUtils to get the actual file by uri
File file = FileUtils.getFile(this, fileUri);
Instead of that I decided to use intent to get the file using the code below.
uploadButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Picture"), PICK_IMAGE_REQUEST);
}
});
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PICK_IMAGE_REQUEST && resultCode == Activity.RESULT_OK
&& data != null && data.getData() != null) {
Uri fileUri = data.getData();
Log.d(LOG_TAG, "fileUri " + fileUri.toString());
try {
File file = new File(fileUri.getPath());
Log.d(LOG_TAG, "file " + file.toString());
// create RequestBody instance from file
RequestBody requestFile =
RequestBody.create(MediaType.parse("multipart/form-data"), file.getAbsoluteFile());
// MultipartBody.Part is used to send also the actual file name
MultipartBody.Part body =
MultipartBody.Part.createFormData("picture", file.getName(), requestFile);
// add another part within the multipart request
String descriptionString = "POINT(12.9085608 77.6106535)";
RequestBody location =
RequestBody.create(
MediaType.parse("multipart/form-data"), descriptionString);
// finally, execute the request
Call<ResponseBody> call = mAbService.uploadImage(location, body);
call.enqueue(new Callback<ResponseBody>() {
@Override
public void onResponse(Call<ResponseBody> call,
Response<ResponseBody> response) {
Log.v(LOG_TAG, "success");
}
@Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
Log.e(LOG_TAG, t.getMessage());
}
});
} catch (Exception e) {
Log.d(LOG_TAG, "file failed");
}
}
I am unable to get the paths correct to be able to upload the file to my server.
08-10 01:28:36.564 20093-20093/com.sudhirkhanger.app.test D/TestActivityFragment: fileUri content://com.android.providers.media.documents/document/image%3A57373
08-10 01:28:36.564 20093-20093/com.sudhirkhanger.app.test D/TestActivityFragment: file /document/image:57373
08-10 01:28:36.658 20093-20093/com.sudhirkhanger.app.test E/TestActivityFragment: /document/image:57373: open failed: ENOENT (No such file or directory)