Upload Files from Android to Server Using Multipart Post Entity

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.'
                )
            );

Written by Arvind Bhardwaj

Arvind is a certified Magento 2 expert with more than 10 years of industry-wide experience.

Website: http://www.webspeaks.in/

34 thoughts on “Upload Files from Android to Server Using Multipart Post Entity

  1. 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

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

  3. 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….

  4. 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…

  5. 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:xampphtdocstrytrytrytry.php on line 7

    please help.. please

  6. Excellent goods from you, man. I’ve understand your stuff previous to and you’re just extremely magnificent.
    I actually like what you have acquired here, really like what you’re stating and the way in which
    you say it. You make it enjoyable and you still care for to keep it
    wise. I can’t wait to read much more from you.
    This is actually a terrific site.

  7. Have you ever considered about adding a little bit more than just your articles?
    I mean, what you say is fundamental and everything.
    Nevertheless think of if you added some great images or video clips to give your
    posts more, "pop"! Your content is excellent but with pics and video clips, this site could undeniably be one of the best in its niche.
    Great blog!

  8. It's the best time to make some plans for the future and it's time to be happy.
    I have read this post and if I could I want to suggest you few interesting things or advice.
    Maybe you could write next articles referring to this article.
    I desire to read even more things about it!

  9. This is the perfect site for anyone who hopes to understand this topic.
    You know a whole lot its almost hard to argue with you (not that I really will
    need to…HaHa). You certainly put a fresh spin on a subject that's been discussed for ages.
    Great stuff, just excellent!

Comments are closed.