Uploading files to HTTP server using POST on Android.

This tutorial shows a simple way of uploading data (images, MP3s, text files etc.) to HTTP/PHP server using Android SDK.

It includes all the code needed to make the uploading work on the Android side, as well as a simple server side code in PHP to handle the uploading of the file and saving it. Moreover, it also gives you information on how to handle the basic autorization when uploading the file.

When testing it on emulator remember to add your test file to Android’s file system via DDMS or command line.

What we are going to do is set the appropriate content type of the request and include the byte array as the body of the post. The byte array will contain the contents of a file we want to send to the server.

Below you will find a useful code snippet that performs the uploading operation. The code includes also server response handling.

HttpURLConnection connection = null;
DataOutputStream outputStream = null;
DataInputStream inputStream = null;
String pathToOurFile = "/data/file_to_send.mp3";
String urlServer = "http://192.168.1.1/handle_upload.php";
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary =  "*****";
 
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize = 1*1024*1024;
 
try
{
    FileInputStream fileInputStream = new FileInputStream(new File(pathToOurFile) );
 
    URL url = new URL(urlServer);
    connection = (HttpURLConnection) url.openConnection();
 
    // Allow Inputs & Outputs.
    connection.setDoInput(true);
    connection.setDoOutput(true);
    connection.setUseCaches(false);
 
    // Set HTTP method to POST.
    connection.setRequestMethod("POST");
 
    connection.setRequestProperty("Connection", "Keep-Alive");
    connection.setRequestProperty("Content-Type", "multipart/form-data;boundary="+boundary);
 
    outputStream = new DataOutputStream( connection.getOutputStream() );
    outputStream.writeBytes(twoHyphens + boundary + lineEnd);
    outputStream.writeBytes("Content-Disposition: form-data; name=\"uploadedfile\";filename=\"" + pathToOurFile +"\"" + lineEnd);
    outputStream.writeBytes(lineEnd);
 
    bytesAvailable = fileInputStream.available();
    bufferSize = Math.min(bytesAvailable, maxBufferSize);
    buffer = new byte[bufferSize];
 
    // Read file
    bytesRead = fileInputStream.read(buffer, 0, bufferSize);
 
    while (bytesRead > 0)
    {
        outputStream.write(buffer, 0, bufferSize);
        bytesAvailable = fileInputStream.available();
        bufferSize = Math.min(bytesAvailable, maxBufferSize);
        bytesRead = fileInputStream.read(buffer, 0, bufferSize);
    }
 
    outputStream.writeBytes(lineEnd);
    outputStream.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
 
    // Responses from the server (code and message)
    serverResponseCode = connection.getResponseCode();
    serverResponseMessage = connection.getResponseMessage();
 
    fileInputStream.close();
    outputStream.flush();
    outputStream.close();
}
catch (Exception ex)
{
    //Exception handling
}

If you need to authenticate your user with a username and password while uploading the file, the code snippet below shows how to add it. All you have to do is set the Authorization headers when the connection is created.

String usernamePassword = yourUsername + “:” + yourPassword;
String encodedUsernamePassword = Base64.encodeToString(usernamePassword.getBytes(), Base64.DEFAULT);
connection.setRequestProperty (“Authorization”, “Basic ” + encodedUsernamePassword);

Let’s say that a PHP script is responsible for receiving data on the server side. Sample of such a PHP script could look like this:

<?php
$target_path  = "./";
$target_path = $target_path . basename( $_FILES['uploadedfile']['name']);
if(move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $target_path)) 
{
    echo "The file ".  basename( $_FILES['uploadedfile']['name']).
 " has been uploaded";
} 
else
{
    echo "There was an error uploading the file, please try again!";
}
?>;

Code was tested on Android 2.1 and 4.3. Remember to add permissions to your script on server side. Otherwise, the uploading won’t work.

chmod 777 uploadsfolder

Where uploadsfolder is the folder where the files are uploaded. If you plan to upload files bigger than default 2MB file size limit. You will have to modify the upload_max_filesize value in the php.ini file.

124 thoughts on “Uploading files to HTTP server using POST on Android.

  1. I have tested that solution on Android 2.1 and it worked, also my friend used it and it was ok. Maybe you are developing for a different version of Android, hard to troubleshoot.

  2. What i find difficult is to find a blog that can capture me for a minute but your posts are not alike. Keep it like this.

  3. Reecon,

    Thanks a million for this post, you are a legend. I was fooling around for 2 days trying to get this to work. There are so many versions of this same code floating around on the web that are crap.

    Made two minor changes to make it work:

    #1
    String urlServer = “192.168.1.1/handle_upload.php”; –> should use http://
    String urlServer = “http://192.168.1.1/handle_upload.php”;

    #2
    serverResponseCode = conn.getResponseCode();
    serverResponseMessage = conn.getResponseMessage(); –> vars not declared, conn should be connection (i assume)

    int serverResponseCode = connection.getResponseCode();
    String serverResponseMessage = connection.getResponseMessage();

    Again thanks from Ireland !!

    g_bog

      • hiiiiiiiiiiiii please help me,
        my php page handle_upload.php ganerate error
        Notice: Undefined index: uploadedfile in C:wampwwwuploadshandle_upload.php on line 3

        • HI Azhar:
          my php file

          If u need to upload more than 2 MB files you should change in ini file.. Then only it accepts maximum 120 MB
          NOTE: You should provide “uploadedfile” in content disposition..

  4. your code is very great. thanks for sharing.
    But is still have a little trouble,

    I’m trying to upload a database file from system database.
    here is the path :

    String pathToOurFile = “/data/data/com.android.providers.contacts/databases/contacts2.db”;

    but when i try to lookup in upload folder in web server.
    there is no uploaded file, Could you help me to solve this problem?

    Many Thanks,
    Hendra-1

    • Have you checked whether read/write permissions are enabled in that folder? Also, what is the response message received from server? It will be easier to troubleshoot. Cheers!

  5. I tried the code and i’m posting to PHP. the php code gets called because i’m writing to a log file but the file is not uploaded.
    I tried from the server with a test page and uploaded to same location android is trying and that works. It looks like $_FILES is empty.
    please help!

  6. i tried your code…php says “There was an error uploading the file, please try again! ” and logcat says ” Failure starting core service Java Lang SecurityException”. What can i do to solve this problem?help me please…

  7. I had the problem than post #16 , the solution was :
    chmod 777 folderuploads

    Where folderuploads is the folder where the files are uploaded.

    Im using it with android 2.2.

    Thanks for this tutorial!

  8. i tried your code and its working fine when the file size is less than 2 MB, any idea how to overcome this problem.

    • In the configuration of the server, modify the “upload_max_filesize” up to 20M or whatever (by default is just 2M and is not enough) in the php.ini file.

  9. Hi ! Thanks for your code ! it works very well. Just one thing, do you know how to monitor the upload progress ? data seems to be sent directly to a buffer and the “write methode” don’t wait the data to be sent before write again …

  10. thank you very much for your tutor because i was really depressed with file upload problem before finally i found your tutor…

    once again thank you very much…

  11. thank you very much it is great :)))) but the problem I can only upload files of size <= only 2 mega: (((
    is that we can increase the buffer size??
    to download files larger than 2 mega.
    if so how I'm stuck and thank you very much ^ ^
    thanks:))

  12. Hi. I used to use a method like yours, but then I read in the doc that FileInputStream.available() is not a reliable method and you should use file.length() instead.

  13. The code only uploads files less than 2 MB. I guess, its a problem of server side …… server returns message ‘ ok ‘ after upload completed. Beside, i checked bytesAvailable value at logcat & its last value is 0. So it can be said , full data has been passed to server but for any unknown reason server is not accepting the full data. So, if you have solved this problem already / if you find any solution of it , please let me know. Thanks …….

  14. Thanks a lot for the article… The client side is perfect.. But i have a tomcat 6.0 server.. Can i run this php script on my tomcat?? If yes, How do i do it.. If no, what server should i use??? Please reply as fast as you can.. Thanks..

      • Sorry for the really really late reply.. I too used the apache server and modified the script to dump the uploaded files into a database.. Its working fine… Now I’m working on downloading files from that database using http GET and a similar php script. Hopefully that’ll work out too.. Thanks….

  15. Thanks dude, works fine for me on Android 2.2. For Android noobs like me: Check out the DDMS perspective in eclipse (I didn’t even know it before this) and take care to set your server’s upload capacity high enough.

  16. Hi,
    can anyone please tell me how can we pass additional variable (eg: userID)?

    I need to pass the userID together with the file to upload, so that i can rename the file with the userID+Original file name.
    This is to allow another user to upload different file with the same name.

    Thanks~

  17. 01-30 14:50:34.490: WARN/System.err(4664): java.net.ProtocolException: can’t open OutputStream after reading from an inputStream

  18. hi.. i’m not able to view any php file on the browser in my emulator, but the same php file on my pc browser works fine..
    on the emulator, all i get is a blank screen for any php file. (after giving the url “http://10.0.2.2:8080/MyWebProject/upload.php”)
    And for the php file you have given above, it says “undefined index” on line 3,4 that is for the indices “uploadedfile” and “tmp_name”..on the pc browser
    please help, i’m new and i don’t know how to run php files on the android emulator, i use xampp to run it, and for android’s sake, i changed the document root
    to the path of my workspace in eclipse, i’m still not able to fix it up, please do help

  19. I’m trying to use this code, but i get a SocketTimeoutException in getResponseCode()
    The code was hanging the thread, but after i set
    connection.setReadTimeout(10000);
    It throws the exception now.
    Don’t know whats wrong, can you help me?

  20. If I want to use an apache server, do I need to install apache separately or is there a built-in plugin for android?

  21. I like this code a lot because it writes directly to the HttpConnection output buffers from the input stream. My question is for how do you handle the form data (some people call this extra parameters). It seems the listed code does not consider UTF-8 characters or blank spaces in filenames. How can the upload code be corrected to support this?

  22. hi.. itz a gr8 tutorial! thanx a ton!! :)
    i also want to store the name of the uploaded file in the database.. can you tell me how can i do tha?

  23. Hi Rafa, thank you for your great tutorial.
    I tried this and I got Address family not supported by protocol.
    I’ve added INTERNET and WRITE_EXTERNAL_STORAGE permission to my manifest file.
    I couldn’t find anything significant in google either.
    you have any idea ?

    Thank you

  24. Thank you for great code. But is there anyway we can specify additional parameters (eg. specify which uploaded file belongs to which user) in POST data?

  25. Hi,
    This works great. and thank you so much for the code. Can you please post some code to receive the uploading data using an ASP.net server side instead in PHP? I am really stuck with this and I just can’t fix it by my self. So please please try to post some code , it will be a great help, thanks alot

    Saminda

  26. outputStream = new DataOutputStream( connection.getOutputStream() );
    returns NetworkOnMainThreadException from android.os 4.1.1
    Should it be changed to a thread?

  27. This is a very nice tutorial..I really want to get it run since I am getting error of connection time out…Also do I need to install php on my local apache tomcat server? if answer is yes how can i do that…cause I followed several tutprial posted on web nothing works…PLease help me I really need to get this done..Thanks

  28. this worked AWESOME!! Thanks for the tutorial!! I fought forever to get this working, not because of your code, but because I needed to log into the connection with username and password. I finally got it working by adding in this snippet after you create the connection:

    // Put the authentication details in the request
    if (mUsername != null) {
    String usernamePassword = mUsername + “:” + mPassword;
    String encodedUsernamePassword = Base64.encodeToString(usernamePassword.getBytes(), Base64.DEFAULT);
    connection.setRequestProperty (“Authorization”, “Basic ” + encodedUsernamePassword);
    }

    Then do the allow inputs and outputs and turn use caches to false and the rest of the code. Now it works great. I do have one issue. I can’t run the php script from anything other than the root directory. Is that normal? I can save the file to any other folder in the directory but can’t run the php from other folders.

    Thanks again, you RULE!! :)

  29. Can you please tell me where have you saved your mp3 file? You have written
    String pathToOurFile = “/data/file_to_send.mp3″;
    I am saving my jpeg image file in drawable. What should be the path for this?

    Thanks in Advance

  30. Hi, cool post, however I have a problem.

    outputStream = new DataOutputStream( connection.getOutputStream() );
    Throws an exception of null.

    Testing on the Galaxy Tab 2, android 4.1.
    My code is identical to the above bar the url, which is reachable in the tablets browser.

    Any advice on this would be greatly appreciated.

  31. I am developing an application in which from my mobile I am sending files to the WiFi printer by IP address and port number, which are .txt, .png, .jpg, .doc. They should be printed from the printer. I have tried your code but my problem is in this line
    String urlServer = “http://192.168.1.1/handle_upload.php”;
    Instead of I am writing
    String urlServer = “http://192.168.1.1:myPort”;
    I am provideng IP and port number of my WiFi printer on which it connects.
    But I am not getting any output.
    What is the problem?
    What changes are required to be done so that I can get the output…?

    I am also giving permissions in Manifest file..

  32. You are missing the content type. Right after this line:

    outputStream.writeBytes(“Content-Disposition: form-data; name=”uploadedfile”;filename=”” + pathToOurFile +””” + lineEnd);

    Add something like this:

    outputStream.writeBytes(“Content-Type: image/jpeg” + lineEnd);

    Obviously, change to the appropriate type. Without this it will not work with some PHP servers.

  33. My brother suggested I might like this web site.
    He was entirely right. This post

    truly made my day. You can not imagine simply how much time I had spent for this

    info! Thanks!

  34. Hi! I’ve been following your web site for a long time now and finally got the bravery to go ahead and give you a shout out from Porter Texas! Just wanted to tell you keep up the fantastic work!

  35. Have you ever considered about adding a little bit more
    than just your articles? I mean, what you say is important and all.
    However think about if you added some great pictures or video clips to give your posts more, “pop”!
    Your content is excellent but with pics and videos, this website
    could undeniably be one of the best in its field.

    Fantastic blog!

  36. Hi how i can use this example to send data from local storage to server any kind of data thank you for the example.

  37. Usually I do not read post on blogs, but I wish
    to

    say that this write-up very pressured me
    to check out and do it! Your

    writing taste has been surprised me. Thanks,
    quite great post.

  38. I tried to use this code in my application, but I got an internal server error 500. The directory is with the right permissions on the server. is this error because of the file size? how can I chenge the maximum size accepted for an image since i´m not using an php configuration file? thank you

  39. Right here is the perfect web site for anybody who wants
    to understand this topic. You understand so much its almost hard to argue with
    you (not that I personally would want to…HaHa).
    You definitely put a new spin on a topic that has been discussed for years.

    Excellent stuff, just excellent!

  40. Pingback: Android Code for Corresponding Server Side Code | BlogoSfera

  41. i tired to upload my file on wamp server. handle_upload php file generate error when i run on wamp server. please help me my file does not uploaded on server.
    please give me solution.

  42. hi, Your coding works good for me.. Actually I upload mp3 file it’s uploaded really good.. Thank you…
    But if i send large file it fails please help me.. I am new to android.. Thanks in advance

  43. Pingback: PHP can't find uploaded file comes from androidCopyQuery CopyQuery | Question & Answer Tool for your Technical Queries,CopyQuery, ejjuit, query, copyquery, copyquery.com, android doubt, ios question, sql query, sqlite query, nodejsquery, dns quer

  44. My file length is 173665, I get error stating :
    File length(30642): 173665
    Server Response Code(30642): 404
    Server Response Message(30642): Not Found
    Server Response Time(30642): 2014_01_19_10:27:16
    Send file Exception(30642): length=65; regionStart=-1; regionLength=66
    System.err(30642): java.lang.StringIndexOutOfBoundsException: length=65; regionStart=-1; regionLength=66

    what could be the problem ?

  45. I am simple blowen by the quality of idea I have
    actually obtained in this blog. It is blogs like this that must be shared and voted for around
    the internet. By the wayu00e7 you have motivated me to create a blog post
    in my blog on a similar topic.

  46. I’m not sure where you’re getting your info,
    but great topic. I needs to spend some time learning much more or understanding more.
    Thanks for wonderful information I was looking for this info for my mission.

Leave a Reply