无法使用HttpClient从Android设备相机发布图像

时间:2012-06-08 18:05:10

标签: android post httpclient android-camera

我正在尝试使用Apache Commons HttpClient在Android设备上发布相机拍摄的图像和其他一些参数。

我的帖子请求正常,服务器可以正常读取参数,但我的图片无法上传。上传由PHP脚本处理,我可以确认正确的HTTP Post会导致图像成功上传,因为我已经使用HTML表单测试了PHP脚本。我也可以在下面的代码中确认照片!= null。

HttpClient httpClient = new DefaultHttpClient();
HttpPost postRequest = new HttpPost("http://myurl.com/upload.php");
MultipartEntity reqEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);

if (photo != null) {
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    photo.compress(CompressFormat.JPEG, 75, bos);
    byte[] data = bos.toByteArray();

    ByteArrayBody bab = new ByteArrayBody(data, "submission-1.jpg");

    reqEntity.addPart("file", bab);
}

reqEntity.addPart("date", new StringBody(date));
reqEntity.addPart("lat", new StringBody(latitude));
reqEntity.addPart("long", new StringBody(longitude));
reqEntity.addPart("name", new StringBody(name));
reqEntity.addPart("email", new StringBody(email));
reqEntity.addPart("comments", new StringBody(comments));

postRequest.setEntity(reqEntity);
HttpResponse response = httpClient.execute(postRequest);

1 个答案:

答案 0 :(得分:0)

我想出来了,希望其他人会觉得这很有帮助。我所要做的就是将文件类型添加到这一行:

ByteArrayBody bab = new ByteArrayBody(data, "image/jpeg", "submission.jpg");