使用多部分条目将图像从SD卡发送到服务器

时间:2011-09-22 07:33:08

标签: android image multipart

我正在创建一个Android应用程序,我将图像从/mnt/sdcard/DCIM/Camera/IMG_20110922_124932.jpg发送到服务器以通过多部分请求..任何人都可以帮助我.... 任何帮助将不胜感激.. 感谢..

2 个答案:

答案 0 :(得分:0)

以下是我用于将图像发送到服务器的多部分帖子的简单示例:

public void MultipartPost(){
    DefaultHttpClient httpClient = new DefaultHttpClient();
    HttpPost postRequest = new HttpPost(url);
//Set Credentials
    String auth = User + ":" + Pass;
    byte[] bytes = auth.getBytes();
    postRequest.setHeader("Authorization", "Basic " + new String(Base64.encodeBytes(bytes)));


    try {


        MultipartEntity mpC = new MultipartEntity();

        //Create stringbody for the filename
    StringBody sbPicID = new StringBody("123.jpg");

        //get a file reference from the image on the SD card
    File fle = new File("full path to the file");

        //create a filebody from the file
    FileBody fb = new FileBody(fle);

    //Add the file name and filebody to the Multipart Entitiy
    mpC.addPart("myImage", sbPicID);
    mpC.addPart("myImage", fb);

       //Set the entitiy of the post request to your Multipart
        postRequest.setEntity(mpC);

       HttpResponse res;

   //execute the post request
       Log.d(TAG,"Starting Send...");
   res = httpClient.execute(postRequest);
   Log.d(TAG, res.getStatusLine().getReasonPhrase());
   Log.d(TAG, res.getStatusLine().getStatusCode());
   res.getEntity().getContent().close();
   Log.d(TAG,"After Close");

   } catch (ClientProtocolException e) {
        e.printStackTrace();
   } catch (IOException e) {
        e.printStackTrace();
   } catch (Exception e){
        e.printStackTrace();
   }

    }

答案 1 :(得分:0)

请参阅上周我回答的[此问题] [1]的接受答案。它与上面的答案非常相似,但也包含一些示例PHP代码来获取图像。

JSON and upload image to server