How can my app ask the user to choose a file and then upload that file to the server? The file will either come from a browser based download or it will come from the camera stored it.
I expect that the user will choose the file using whatever file browser will check the folder that these two things write to. Then I will store the path to the file and make the upload at the time the email is sent.
Please tell me how to choose the file and if there is a way to upload the file using HttpPost
. (if not, I will write separate upload code, but I will still need to be able to get the user to choose the file.)
Edit: Found the file chooser code from the Android Email App Source Code. There is some kind of built in file chooser that uses IDs instead of the regular file system. The app had it filtered to image/* type, but if you remove that filter it will ask if it should use gallery (which has a menu link to camera) or if it should use a Sound file or record a new sound file. The starting place is src/com/android/email/activity/MessageCompose.java
. The method is onOptionsItemSelected
and it has a switch
case:
for attachments.
It turns out that the Android SDK includes only part of the apache library and therefor HttpClient does not exist. I will get the data to be uploaded instead with multiple requests and put in Base64 data in one of the POST parameters.
There is no dedicated file chooser on android, so you must create your own: How to create file chooser in Android?
You didn't specify the protocol when you said you need to upload to server, so I'll assume that you mean classic Http file upload (POST with multipart mime). Example taken from here.
try {
DefaultHttpClient httpclient = new DefaultHttpClient();
File f = new File(filename);
HttpPost httpost = new HttpPost("http://myremotehost:8080/upload/upload");
MultipartEntity entity = new MultipartEntity();
entity.addPart("myIdentifier", new StringBody("somevalue"));
entity.addPart("myFile", new FileBody(f));
httpost.setEntity(entity);
HttpResponse response;
response = httpclient.execute(httpost);
Log.d("httpPost", "Login form get: " + response.getStatusLine());
if (entity != null) {
entity.consumeContent();
}
success = true;
} catch (Exception ex) {
Log.d("FormReviewer", "Upload failed: " + ex.getMessage() +
" Stacktrace: " + ex.getStackTrace());
success = false;
} finally {
mDebugHandler.post(mFinishUpload);
}