2012-02-22 95 views
2

我一直在尋找解決方案,並且遇到了多部分和不同的設置,但我似乎無法使其正常工作。Android:通過POST發送圖像

這是我到目前爲止。

編輯:我得到的服務器端錯誤是500.我認爲這是因爲我發送的數據對於一個請求來說太大,或者格式不正確。

    ByteArrayOutputStream bao = new ByteArrayOutputStream(); 

        bm.compress(Bitmap.CompressFormat.JPEG, 90, bao); 

        byte [] ba = bao.toByteArray(); 

        String ba1=Base64.encodeToString(ba,Base64.URL_SAFE); 

        mParams.add(new BasicNameValuePair("story[image]",ba1)); 

    HttpClient httpclient = new DefaultHttpClient(); 
    HttpPost httppost = new HttpPost(mPath); 
    // Add your data 
    try 
    { 
     httppost.setHeader("Authorization", Base64.encodeToString(new StringBuilder(sssss).append(":").append(ssssss).toString().getBytes("UTF-8"), Base64.URL_SAFE|Base64.NO_WRAP)); 
     httppost.setEntity(new UrlEncodedFormEntity(mParams)); 
     HttpResponse rH = httpclient.execute(httppost); 
     Log.v(TAG, "response: " + rH.toString()); 
     int f = 0; 
    } 
    catch(HttpResponseException e) 
    { 
     Log.e(TAG, e.getLocalizedMessage()); 
     Log.e(TAG, e.getMessage()); 
     e.printStackTrace(); 
    } 

回答

5

這是我昨天做了,也許這將有助於

 Bitmap bitmapOrg = images.get(0); 

     ByteArrayOutputStream bao = new ByteArrayOutputStream(); 

     String upload_url = prepare_upload_url(); 
     bitmapOrg.compress(Bitmap.CompressFormat.JPEG, 90, bao); 

     byte[] data = bao.toByteArray(); 

     HttpClient httpClient = new DefaultHttpClient(); 
     HttpPost postRequest = new HttpPost(upload_url); 
     MultipartEntity entity = new MultipartEntity(
       HttpMultipartMode.BROWSER_COMPATIBLE); 

     //Set Data and Content-type header for the image 
     entity.addPart("file", 
       new ByteArrayBody(data, "image/jpeg", "file")); 
     postRequest.setEntity(entity); 
     try { 

      HttpResponse response = httpClient.execute(postRequest); 
     //Read the response 
      String jsonString = EntityUtils.toString(response.getEntity()); 
      Log.v(ProgramConstants.TAG, "after uploading file " 
        + jsonString); 

     } catch (ClientProtocolException e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
     } catch (IOException e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
     } 
+0

會在哪裏設置了POST信息。 EG:我試圖將post [image]的值設置爲圖像數據。 – TylerKinkade 2012-02-22 15:02:41

+0

啊。我用名爲'file'的文件名附加了圖像字節數組。 entity.addPart(「file」,new ByteArrayBody(data,「image/jpeg」,「file」))我正在使用它將圖像發佈到App Engine服務器 – 2012-02-22 15:05:40

+0

Thanks man!現在讓我在這個問題上頭疼一陣。 :) – TylerKinkade 2012-02-22 15:09:09