Uploading files to HTTP server using POST. Android SDK.

This code uploads data (images, mp3′s, text files etc..) to HTTP server. Original code can be found here http://www.anddev.org/upload_files_to_web_server-t443-s15.html, however I added server response handling and also some fixes.

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

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

// Enable POST method
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
}

On server side PHP script is responsible for receiving data. Sample of such a PHP script:

<?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 it works. Remember to add permissions to your script on server side.

About these ads

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

  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

  4. Thank you soooooooo much. A lot of people say they can do this but you have done it with the smallest amount of code too. Thank you again.

  5. 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!

  6. 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!

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

  8. 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!

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

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

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

  12. This code works for me but can’t access the file through the browser – shows a 403 error… any thoughts? Thanks!

  13. 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:))

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

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

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

    • I used Apache. This script is only an example. You should write your own, adding features you want to have on your server or process the file in some way. It is all up to you. Cheers!

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

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

  18. 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~

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

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

  21. 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?

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

  23. 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?

  24. 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?

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

  26. 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?

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

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

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

  30. 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!! :)

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s