【发布时间】:2011-06-14 10:58:09
【问题描述】:
您好,
我无法从我的 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);
}
}
post 函数(推荐)在哪里:
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,它会正常记录。
还有什么建议吗?
非常感谢,
【问题讨论】:
-
我发现 http 帖子必须从异步任务中完成,否则它们就不会发生。我一直在考虑在发布和获取数据方面做类似的事情,并且需要在异步任务中将帖子包装到 url。 (developer.android.com/reference/android/os/AsyncTask.html)