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.
- Download the library to your host development system.
- Create a new folder, libs, in your Eclipse/Android project.
- 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).
- 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).
- 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 |
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.'
)
);
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?
This is owesome
this is owesome
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
it helped me a lot)
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’]
Thanks for notice 🙂
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
Thanks a ton!!! 😀
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
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
Good post but I was wondering if you could write a litte more on this topic?
I’d be very grateful if you could elaborate a little bit further.
Thanks!
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.
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!
My famuly mеmbers always say that I am kolling
my time hsre at web, but I know I am getting familiarity
every day bby reading thes pleasant articleѕ or reviews.
I am sure this paragraph has touched all the internet visitors, its really
really pleasant post on building up new blog.
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!
Right away I am ready to do my breakfast, when having my breakfast coming again to
read other news.
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!
I am truly thankful to the holder of this site who has shared this great article at
at this time.