Search code examples
androidimagemultipart

Send images from sdcard to server using multipart entry


I am making an android app in which i am sending image to server from /mnt/sdcard/DCIM/Camera/IMG_20110922_124932.jpg to serverthrough multipart request .. Can anybody help me out.... Any help will be appreciated.. Thanks..


Solution

  • Here is a simple example of a multipart post that I use to send images to a server:

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