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.
hi..using this my application is crashing; while trying to send an image..
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.
Thanks,
This code works !!
hi Prateek,can you send the above example code with a zip file
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.
Hi ,
thanks for sharing (:
is there any limit with the file size?
I think there is no limit of the file size but I did not check it, that’s only a guess.
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
Thanks, I added fixes you mentioned. Greetings from Poland!
cant i change lake this
String urlServer = “http://namedomain.com/handle_upload.php”
and this work in andorid 4
doesn’t work for me with 2.2
I’d really like to get a full working code for 2.2
@Efefes Check out my post
damn cool tut !!
Big thank to u guys
Thanks for the post
how to send multiple files
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.
I had a problem when using Android 2.2 but http://stackoverflow.com/questions/3204476/android-file-uploader-with-server-side-php
shows a good Java side code that is only a little different from yours but it works with 2.2
To see the code you have to scroll down to the bottom of the page
Hi,
i did not get the image with this code and i can’t find what’s the problem please anyone help me
Thanks, very valuable code..
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!
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!
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…
Try adding the permissions in manifest
Thanks a lot man, this code has really helped me out
Thank you!!!
Ur great!!
Fantastic Work!!
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!
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.
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 …
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…
Have resolved it!!
Thanks for this snippet of code
This code works for me but can’t access the file through the browser – shows a 403 error… any thoughts? Thanks!
Check out that link, it may be useful http://www.cyberciti.biz/faq/apache-403-forbidden-error-and-solution/
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:))
Thankyou so much …..
This is very good code sample. Can you also port this code to WP7.1 windows phone 7.1 sdk, which is C# ASP.NET.
thx for this post..guys but i can’t upload mp3. file in my server folder. there is no error.
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.
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 …….
I got the solution. Local server (WAMP server) just accepts files of 2 MB as it is configured. You just have to change some values of wamp server configuration to upload big size files.Here is the link of how to change configuration of wamp server – http://www.wampserver.com/phorum/read.php?2,67758,67776.
I got Resource Not Found Exception…
How to resolve it???
how will i send some extra data with file on the server??
What do you mean by “extra data”?
like other parameters key .. how can we send text with this
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….
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.
tanx it worked
1001 Thanks
Hi ,
I want to do like this but I need to send to a php server like this :
http://sitename.com/phpfile.php?act=abc&file=filname
how can I send such data from android ? The file I am sending is an image.
and can I use dos.writeBytes ?
thank you
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~
Het Miguel.. Check this..
http://coderzheaven.com/2011/08/how-to-upload-multiple-files-in-one-request-along-with-other-string-parameters-in-android/
But make sure to download and include the mentioned JAR files in you project.. Good Luck..
01-30 14:50:34.490: WARN/System.err(4664): java.net.ProtocolException: can’t open OutputStream after reading from an inputStream
thanks for the good piece of code
How to check whether the server is available and it is not down before uploading the file?
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
Hi, how can I do if I have to do also the BasicScheme authentication?
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?
If I want to use an apache server, do I need to install apache separately or is there a built-in plugin for android?
pls i need help.i tried the code above and it kept saying http://localhost connection refused but i have add the in my app what should i do pls
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?
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?
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
Where does the file gets uploaded?
Hello can you please tell me what all permissions are required in running the code??
This code is not working on 4.0.3. Can anyone explain why?
Thank you very much! Great code, works perfectly! Great explanation and tutorial.
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?
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
Thanks alot for ur code !!!
I suffered alot trying to find a working code and all of them aren’t !!!
Works Great !!!
outputStream = new DataOutputStream( connection.getOutputStream() );
returns NetworkOnMainThreadException from android.os 4.1.1
Should it be changed to a thread?
Thank u for your code..it is very helpfull to me..thank u..
Amazing thanks so much. Works on my S2 running JB
Can I use this code for ASP.net . Because my service based on ASP.net
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
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!!