问候,Android:上传照片
我在从我的Android手机上传照片时遇到问题。下面是我使用提示用户选择照片的代码:
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?
}
}
}
所以我有位图B,但我不知道下一步该怎么做?
我发送POST请求以下代码:
List<NameValuePair> params = new ArrayList<NameValuePair>(2);
params.add(new BasicNameValuePair("someValA", String.valueOf(lat)));
params.add(new BasicNameValuePair("someValB", String.valueOf(lng)));
new HttpConnection(handler).post("http://myurl.com/upload.php",params);
我怎么能一个位图图像挂钩到这一点?我搜索谷歌的年龄,无法找到一个好办法。
我希望有人能帮忙。
很多感谢,
好吧,我已经试过CHIRAG Shah的建议。这里是我的代码:
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);
}
}
在帖子函数(推荐):
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();
}
}
但是myurl.com/ajax/uploadPhoto.php越来越什么。我创建了一个PHP日志来记录uploadPhoto.php上的任何活动,并且没有任何内容显示出来。值得注意的是,如果我只是直接在网页浏览器中输入myurl.com/ajax/uploadPhoto.php,它会很好地记录。
还有更多建议吗?
非常感谢,
我发现所谓的onclick该http帖子必须从异步任务完成,否则他们就不会发生。我一直在寻找类似发布和获取数据的东西,并且需要在异步任务中将帖子包装到url中。 (http://developer.android.com/reference/android/os/AsyncTask.html) – Tim 2013-11-15 00:19:04