2011-10-20 13 views
7

Ho un URI di un'immagine che è stata presa o selezionata dalla Raccolta che voglio caricare e comprimere come JPEG con una qualità del 75%. Credo di aver ottenuto che con il seguente codice:ByteArrayOutputStream a FileBody

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

Non che io abbia infilato in una ByteArrayOutputStream chiamato bos ho bisogno di poi inserirlo in una MultipartEntity per HTTP POST ad un sito web. Quello che non riesco a capire è come convertire ByteArrayOutputStream in un FileBody.

risposta

14

Utilizzare un ByteArrayBody invece (disponibile dal HTTPClient 4.1), nonostante il suo nome ci vuole un nome di file, anche:

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

Se sei bloccato con HTTPClient 4.0, utilizzare InputStreamBody invece:

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

(Entrambe le classi dispongono anche di costruttori che accettano una stringa di tipo MIME aggiuntiva)

2

spero che possa essere d'aiuto qualcuno, si può citare il tipo di file come "image/jpeg" in FileBody come qui di seguito il codice

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()); 

necessità di aggiungere file jar HttpClient-4.2.2.jar, httpmime-4.2.2.jar nel progetto .

Problemi correlati