【问题标题】:Android - Error Setting Up Content Type When Uploading ImagesAndroid - 上传图片时设置内容类型时出错
【发布时间】: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


【解决方案1】:

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

【讨论】:

  • ContentType.MULTIPART_FORM_DATA 不行,需要设置为“image/jpeg”,但是ContentType类没有提供这个选项。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-11-05
  • 2020-05-02
  • 1970-01-01
  • 1970-01-01
  • 2010-11-27
  • 1970-01-01
相关资源
最近更新 更多