I know my problem has been tackled multiple times already, but I couldn't find anything that would help me with my specific problem.
I have an intent to pick a file anywhere from the system:
private void showFileChooser() {
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("*/*");
intent.addCategory(Intent.CATEGORY_OPENABLE);
try {
startActivityForResult(
Intent.createChooser(intent, "Select a File to Upload"),
FILE_SELECT_CODE);
} catch (android.content.ActivityNotFoundException ex) {
// Potentially direct the user to the Market with a Dialog
Toast.makeText(this, "Please install a File Manager.",
Toast.LENGTH_SHORT).show();
}
}
I pick up this intent here:
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case FILE_SELECT_CODE:
if (resultCode == RESULT_OK) {
// Get the Uri of the selected file
Uri uri = data.getData();
}
and I have an upload method like so:
private void upload(File file){
RequestParams params = new RequestParams();
try {
params.put("fileToUpload", file);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
AsyncHttpClient client = new AsyncHttpClient();
client.post("http://...", params, new AsyncHttpResponseHandler() {
@Override
public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
System.out.println("statusCode "+statusCode);//statusCode 200
}
@Override
public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
}
});
}
the problem is that I don't know how to "marry" the two methods onActivity and upload because I don't know how to process the information I get from the intent so that the AsyncHttpClient can use it.
I tried converting the Uri to an absolute path, but couldn't manage (the solutions online that seemed to work where specifically for images). I also can't "convert" the uri to a file either.
Any way I could do this? Am I missing something?
The ideal solution is to use ContentResolver
and openInputStream()
to get an InputStream
on the content identified by the Uri
, then pass that InputStream
to your HTTP client API for use in uploading.
If your HTTP client API does not support the use of InputStream
or something that could be derived from one (e.g., Reader
), and so you need a File
, use that InputStream
and a FileOutputStream
on some file that you control to make a local copy of the content (e.g., in getCacheDir()
). Then, use your local copy for the file upload operation, and delete the local copy when you are done.