Android - 上载图像时设置内容类型时出错

时间:2014-07-11 11:08:04

标签: php android image-uploading apache-httpclient-4.x apache-httpcomponents

我试图从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();
        }

   }

1 个答案:

答案 0 :(得分:2)

addBinaryBody方法有几个签名。您可以在其中添加contentType,如下所示:

String filename = "imageName.jpg"
multiPartEntityBuilder.addBinaryBody("photo", file, ContentType.MULTIPART_FORM_DATA, filename);

这里是Documentation

如果你想提出另一个ContentType,你可以创建自己的内容,如下所示:

public static final ContentType MYCONTENTTYPE = ContentType.create(
           "image/jpeg", Consts.ISO_8859_1);

这里是Documentation