Android: upload photos [duplicate]
Greetings,
I'm having trouble uploading a photo from my Android phone. Here is the code I'm using to prompt the user to select a photo:
public class Uploader{
public void upload(){
Log.i("EOH","hi...");
Intent photoPickerIntent = new Intent(Intent.ACTION_GET_CONTENT);
photoPickerIntent.setType("image/*");
startActivityForResult(photoPickerIntent, 1);
}
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
if (resultCode == RESULT_OK)
{
Bundle extras = data.getExtras();
Bitmap b = (Bitmap) extras.get("data");
//what do do now with this Bitmap...
//how do I upload it?
}
}
}
So I have the Bitmap b, however I don't know what to do next?
I have the following code for sending POST requests:
List<NameValuePair> params = new ArrayList<NameValuePair>(2);
params.add(new BasicNameValuePair("someValA", String.valueOf(lat)));
params.add(new BasicName开发者_开发问答ValuePair("someValB", String.valueOf(lng)));
new HttpConnection(handler).post("http://myurl.com/upload.php",params);
How can I hook up a Bitmap image to this? I've searched google for ages and can't find a good way of doing it.
I hope someone can help.
Many thanks in advance,
Ok I've tried chirag shah's suggestion. Here is my code:
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
if (resultCode == RESULT_OK)
{
Uri imageUri=data.getData();
List<NameValuePair> params = new ArrayList<NameValuePair>(1);
params.add(new BasicNameValuePair("image", imageUri.getPath()));
post("http://www.myurl.com/ajax/uploadPhoto.php",params);
}
}
where the post function (as recommended) is:
public void post(String url, List<NameValuePair> nameValuePairs) {
HttpClient httpClient = new DefaultHttpClient();
HttpContext localContext = new BasicHttpContext();
HttpPost httpPost = new HttpPost(url);
try {
MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
for(int index=0; index < nameValuePairs.size(); index++) {
if(nameValuePairs.get(index).getName().equalsIgnoreCase("image")) {
// If the key equals to "image", we use FileBody to transfer the data
entity.addPart(nameValuePairs.get(index).getName(), new FileBody(new File (nameValuePairs.get(index).getValue())));
}else{
// Normal string data
entity.addPart(nameValuePairs.get(index).getName(), new StringBody(nameValuePairs.get(index).getValue()));
}
}
httpPost.setEntity(entity);
HttpResponse response = httpClient.execute(httpPost, localContext);
Log.i("EOH",response.toString());
} catch (IOException e) {
e.printStackTrace();
}
}
However myurl.com/ajax/uploadPhoto.php is getting nothing. I've created a PHP log to log any activity on uploadPhoto.php, and nothing is showing up. It's worth noting that if I just type myurl.com/ajax/uploadPhoto.php straight into a web browser, it logs fine.
Any more suggestions?
Many thanks,
If you aren't already. Try wrapping the post to the server in an Async Task and calling the task. I found that the api I am using requires http posts/gets to be done away from the main thread to avoid possible issues locking up the main thread.
It was relatively easy just to set it up as an Async task and that started actually working.
More info on Async tasks : http://developer.android.com/reference/android/os/AsyncTask.html
For a simple example this is one of my async tasks :
private class SomeAsyncTask extends AsyncTask<String, Void, JSONObject> {
@Override
protected JSONObject doInBackground(String... arg0) {
UserFunctions uf = new UserFunctions();
JSONObject res = uf.doPostToServer(arg0[0], arg0[1], arg0[2], getApplicationContext());
return res;
}
@Override
protected void onPostExecute(JSONObject result) {
try {
int success = result.getInt("success");
if(success == 1) {
Intent vcact = new Intent(getApplicationContext(), OtherActivity.class);
vcact.putExtra("id", cid);
startActivity(vcact);
// close main screen
finish();
} else {
Toast.makeText(SomeActivity.this, "Error saving to server. Try again.", Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
and it is called onclick with
new SomeAsyncTask().execute(cid, otherdata, moredata);
精彩评论