【发布时间】:2014-07-11 19:48:36
【问题描述】:
我正在尝试将图像从 Android 应用程序上传到 PHP 服务器。
我正在使用 httpcore 和 httpmime 库。
问题是图像正在上传,但服务器无法将其识别为 JPEG 图像。我需要为图像设置 ContentType,但我找不到方法。
这是我正在使用的方法 -
public void uploadImage(String imagePath) throws ClientProtocolException, IOException
{
// Client-side HTTP transport library
HttpClient httpClient = new DefaultHttpClient();
// using POST method
HttpPost httpPostRequest = new HttpPost("URL_TO_PHP_SERVER");
try {
File file = new File(imagePath);
MultipartEntityBuilder multiPartEntityBuilder = MultipartEntityBuilder.create();
multiPartEntityBuilder.addTextBody("user_id", userID);
multiPartEntityBuilder.addBinaryBody("photo", file);
httpPostRequest.setEntity(multiPartEntityBuilder.build());
// Execute POST request to the given URL
HttpResponse httpResponse = null;
httpResponse = httpClient.execute(httpPostRequest);
// receive response as inputStream
InputStream inputStream = null;
inputStream = httpResponse.getEntity().getContent();
String result;
if (inputStream != null)
result = convertInputStreamToString(inputStream);
else
result = "Did not work!";
Log.v("result", result);
} catch (Exception e) {
e.printStackTrace();
}
}
【问题讨论】:
-
请同时发布你的logcat
-
Mann,我打印来自服务器的响应(Android 部分没有实际错误),它读取文件的类型未知,服务器只接受 JPEG 和 PNG 文件(虽然我正在发送 JPEG 图像)。
-
请检查我的答案:)
标签: php android image-uploading apache-httpclient-4.x apache-httpcomponents