Upload Files from Android to Server Using Multipart Post Entity

25 comments
Uploading files and data from an Android device to a server is not a big deal until you are doing this on a high end (high memory) device. But if the memory of your device is low and the size of the file being uploaded is large, then your android application may crash at some moment giving the 'Out of memory' error. To avoid this 'Out of memory' error while uploading files through android device, you need to use the 'Multipart entity' client by apache. You need to download the jar files and then add to your Android project.


Here are the steps to add the external jar files to your android project.

  1. Download the library to your host development system. 
  2. Create a new folder, libs, in your Eclipse/Android project.
  3. Right-click libs and choose Import -> General -> File System, then Next, Browse in the filesystem to find the library's parent directory (i.e.: where you downloaded it to). 
  4. Click OK and then click the directory name (not the checkbox) in the left pane, then check the relevant JAR in the right pane. This puts the library into your project (physically). 
  5. Right-click on your project, choose Build Path -> Configure Build Path, then click the Libraries tab, then Add JARs..., navigate to your new JAR in the libs directory and add it. (This, incidentally, is the moment at which your new JAR is converted for use on Android.)

Project structure
Project structure

The Java Code:

Necessary imports in your Java file:
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.ContentBody;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONObject;

Here is the Java code that will upload the file and data to the server:
public void upload() throws Exception {
        //Url of the server
        String url = "";
        HttpClient client = new DefaultHttpClient();
        HttpPost post = new HttpPost(url);
        MultipartEntity mpEntity = new MultipartEntity();
        //Path of the file to be uploaded
        String filepath = "";
        File file = new File(filepath);
        ContentBody cbFile = new FileBody(file, "image/jpeg");         

        //Add the data to the multipart entity
        mpEntity.addPart("image", cbFile);
        mpEntity.addPart("name", new StringBody("Test", Charset.forName("UTF-8")));
        mpEntity.addPart("data", new StringBody("This is test report", Charset.forName("UTF-8")));
        post.setEntity(mpEntity);
        //Execute the post request
        HttpResponse response1 = client.execute(post);
        //Get the response from the server
        HttpEntity resEntity = response1.getEntity();
        String Response=EntityUtils.toString(resEntity);
        Log.d("Response:", Response);
        //Generate the array from the response
        JSONArray jsonarray = new JSONArray("["+Response+"]");
        JSONObject jsonobject = jsonarray.getJSONObject(0);
        //Get the result variables from response 
        String result = (jsonobject.getString("result"));
        String msg = (jsonobject.getString("msg"));
        //Close the connection
        client.getConnectionManager().shutdown();
    }
We assume that the server environment is PHP. To receive the data on server side we receive the data as we do for the normal PHP post request.

The Server side code in PHP

<?php
//Receive the data from android
$name = $_POST['name'];
$data = $_POST['data'];

//Receive the file
$file = $_FILES['image']

//process the data

//return response to the server

echo json_encode(
            array(
                'result'=>'success',
                'msg'=>'Report added successfully.'
                )
            );

25 comments

Hello, what would happen if say the network connection is lost. Would the upload pause and pick up from where it left off, or would it need to restart?

hola cual es el codigo completo de php?

Please complete the code is php?

This is not working

The type org.apache.james.mime4j.descriptor.ContentDescriptor cannot be resolved. It is indirectly referenced from required .class files


I got this error
please help

Hi,
I am not able to get the image content.
All text details are available but image not at server. pls help

See if you are receving image like:
$file = $_FILES['image'];

thanks a lot. it helped me. it works

MultipartEntity is deprecated,instead its recommended to use MultipartEntityBuilder

MultiPartEntity is deprecated,its recommended to use MultiPartEntityBuilder instead

can u post server side code in java. We require server side which is implementing REST web-service to receive file uploaded from client...
Help is appreciated....

Can u please post server side having java platform for receiving file uploaded from android client...We are implementing server with REST web-service...if u know..please post asap.
Thanks in advance...

Semicolon is missing at the end of this line $file = $_FILES['image']

Semicolon ";" is missing at the end of this line $file = $_FILES['image']

Very Helpful, Thanks a Lot.

Getting this
I/System.out﹕ [CDS]rx timeout:0
D/Response:﹕ Access Denied

please help I have this error
D/dalvikvm(13079): DexOpt: couldn't find static field Lorg/apache/http/message/BasicHeaderValueParser;.INSTANCE
and this on the server side
D/Response:(13079): Notice: Undefined index: image in C:\xampp\htdocs\trytry\trytry.php on line 7


please help.. please

Please initialize the array and create an element with index 'image'

This method is depreciated :(
pls show another method

I am not able to recieve image

We would love to hear from you...

back to top