2011-09-22 29 views

回答

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

    } 
+0

感謝您的回答,但我必須做更多的搜索 – Aditya1510

0

見接受的答案我上週回答的[這個問題] [1]。它與上面的答案非常相似,但也包含一些示例PHP代碼來獲取圖像。

JSON and upload image to server