2011-10-20 36 views
7

我有一个图像,它是从我想要加载和压缩为75%质量的JPEG库中选取的图像。我相信我已经实现了用下面的代码:ByteArrayOutputStream到一个文件体

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

不,我已经塞进了一个名为bos我需要它,然后才能将其添加到MultipartEntityHTTP POST到网站ByteArrayOutputStream我无法弄清楚的是如何将ByteArrayOutputStream转换为FileBody。

回答

14

使用,尽管它的名字它需要一个文件名,太一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“图像/ 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 。

相关问题