2012-02-22 78 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