2011-10-20 12 views
7

Yüklemek istediğim Galeri'den seçtiğim veya seçtiğim bir görüntüye,% 75 kalite ile JPEG olarak sıkıştırılmış bir Uri'im var. Ben aşağıdaki kodla olduğunu elde ettik inanıyoruz: Ben o zaman bir web sitesine HTTP POST amacıyla bir MultipartEntity eklemek gerekir bos adında bir ByteArrayOutputStream içine sıkışmış olanByteArrayOutputStream içinBir DosyaGörüntü

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

değil. Ne anlayamadığım, ByteArrayOutputStream öğesinin bir FileBody'ye nasıl dönüştürüleceğidir.

cevap

14

kullanın, bir dosya adını alır adına rağmen, çok bir ByteArrayBody yerine (4.1 HTTPClient beri mevcuttur): Eğer HTTPClient 4.0 ile takılıp kalıyorsa

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

yerine InputStreamBody kullanın:

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

(Her iki sınıf da bir addtional MIME türü dizeyi alan kurucular var)

2

umarım yardımcı olabilir Bazı biri, projenizde jar dosyalarını httpclient-4.2.2.jar, httpmime-4.2.2.jar eklemek gerek

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

kod aşağıda FileBody içinde "image/jpeg" olarak dosya türünü bahsedebiliriz .

İlgili konular