【问题标题】:ByteArrayOutputStream to a FileBodyByteArrayOutputStream 到 FileBody
【发布时间】:2011-12-11 13:37:38
【问题描述】:

我有一个图像的 Uri,该图像是从图库中获取或选择的,我想加载并压缩为 75% 质量的 JPEG。我相信我已经通过以下代码实现了这一点:

ByteArrayOutputStream bos = new ByteArrayOutputStream();
Bitmap bm = BitmapFactory.decodeFile(imageUri.getPath());
bm.compress(CompressFormat.JPEG, 60, bos);

并不是我把它塞进了一个名为bosByteArrayOutputStream 中,我需要将它添加到MultipartEntity 中,以便HTTP POST 将它添加到一个网站。 我不知道如何将 ByteArrayOutputStream 转换为 FileBody。

【问题讨论】:

    标签: android image upload http-post


    【解决方案1】:

    改用ByteArrayBody(自 HTTPClient 4.1 起可用),尽管它的名称也需要一个文件名:

    ContentBody mimePart = new ByteArrayBody(bos.toByteArray(), "filename");
    

    如果您无法使用 HTTPClient 4.0,请改用 InputStreamBody

    InputStream in = new ByteArrayInputStream(bos.toByteArray());
    ContentBody mimePart = new InputStreamBody(in, "filename") 
    

    (这两个类也有带有额外 MIME 类型字符串的构造函数)

    【讨论】:

      【解决方案2】:

      我希望它可以帮助一些人,您可以在 FileBody 中将文件类型称为“image/jpeg”,如下代码所示

      HttpClient httpClient = new DefaultHttpClient();
                  HttpPost postRequest = new HttpPost(
                          "url");
                  MultipartEntity reqEntity = new MultipartEntity(
                          HttpMultipartMode.BROWSER_COMPATIBLE);
                  reqEntity.addPart("name", new StringBody(name));
                  reqEntity.addPart("password", new StringBody(pass));
      File file=new File("/mnt/sdcard/4.jpg");
      ContentBody cbFile = new FileBody(file, "image/jpeg");
      reqEntity.addPart("file", cbFile);
          postRequest.setEntity(reqEntity);
                  HttpResponse response = httpClient.execute(postRequest);
                  BufferedReader reader = new BufferedReader(
                          new InputStreamReader(
                                  response.getEntity().getContent(), "UTF-8"));
                  String sResponse;
                  StringBuilder s = new StringBuilder();
                  while ((sResponse = reader.readLine()) != null) {
                      s = s.append(sResponse);
                  }
      
                  Log.e("Response for POst", s.toString());
      

      需要在你的项目中添加jar文件httpclient-4.2.2.jar,httpmime-4.2.2.jar。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2011-02-12
        • 2010-09-09
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-06-02
        相关资源
        最近更新 更多