Friday, January 25, 2008

Yesterday, the whole day i was trying to post a file to a php server. The whole day and evening i tried and failed. I googled, searched in forum and did a lot of other stuffs. I couldn't succed, at last when i was frustrated on me, then i found another tutorial in a forum, this time it worked. mu ha ha :) (Copy paste rulllzz, so i should never try myself anything :(). The code simulates file posting to a php server. So it will work with servers where file upload from a server is supported. Here goes the code

The php code used in server

< ?php

$target_path = "uploads/";

$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!";

? >

The android code goes here


import org.apache.commons.codec.binary.Base64;
import org.apache.http.util.ByteArrayBuffer;

import android.util.Log;

public class HttpFileUploader implements Runnable{

URL connectURL;
String params;
String responseString;
InterfaceHttpUtil ifPostBack;
String fileName;
byte[] dataToServer;

HttpFileUploader(String urlString, String params, String fileName ){
connectURL = new URL(urlString);
}catch(Exception ex){
this.params = params+"=";
this.fileName = fileName;


void doStart(FileInputStream stream){
fileInputStream = stream;

FileInputStream fileInputStream = null;
void thirdTry(){
String exsistingFileName = "asdf.png";

String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "*****";
String Tag="3rd";
//------------------ CLIENT REQUEST

Log.e(Tag,"Starting to bad things");
// Open a HTTP connection to the URL

HttpURLConnection conn = (HttpURLConnection) connectURL.openConnection();

// Allow Inputs

// Allow Outputs

// Don't use a cached copy.

// Use a post method.

conn.setRequestProperty("Connection", "Keep-Alive");

conn.setRequestProperty("Content-Type", "multipart/form-data;boundary="+boundary);

DataOutputStream dos = new DataOutputStream( conn.getOutputStream() );

dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"uploadedfile\";filename=\"" + exsistingFileName +"\"" + lineEnd);

Log.e(Tag,"Headers are written");

// create a buffer of maximum size

int bytesAvailable = fileInputStream.available();
int maxBufferSize = 1024;
int bufferSize = Math.min(bytesAvailable, maxBufferSize);
byte[] buffer = new byte[bufferSize];

// read file and write it into form...

int bytesRead =, 0, bufferSize);

while (bytesRead > 0)
dos.write(buffer, 0, bufferSize);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
bytesRead =, 0, bufferSize);

// send multipart form data necesssary after file data...

dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);

// close streams
Log.e(Tag,"File is written");

InputStream is = conn.getInputStream();
// retrieve the response from server
int ch;

StringBuffer b =new StringBuffer();
while( ( ch = ) != -1 ){
b.append( (char)ch );
String s=b.toString();

catch (MalformedURLException ex)
Log.e(Tag, "error: " + ex.getMessage(), ex);

catch (IOException ioe)
Log.e(Tag, "error: " + ioe.getMessage(), ioe);


Many of the headers included in the above file is not required, i was trying and failing :).

Now to upload file here is the java code from my activity class

public void uploadFile(){

try {
FileInputStream fis =this.openFileInput(NAME_OF_FILE);
HttpFileUploader htfu = new HttpFileUploader("","noparamshere", NAME_OF_FILE);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block

The main advantage is that the way it posts data to the server is similar to a Html Form posting data to a php server. Hope it might be useful for me in future, so i blogged it, if others are helped then that would be great.You can visit for more and more tutorials. Thanks for reading my bad post :)


  1. Anonymous said...
    Good explanation! Exactly what I am looking for, Thanks
    Anonymous said...
    could you explain in brief bcz i am very new to java. but i want this program in my flex project
    Shimul said...
    i dont know how flex works so i think i cannot help u much
    dhileep said...
    no need of flex knowledge required.
    i call applet function from flex.

    you have upload my 'C' drive .doc file to my server in that function

    my mail id is
    dhileep said...
    what i want is exactly u have,
    i want to know how to run your code to get .class file to use in my page

    i am getting some errors.
    dhileep said...
    Thanks a lot for your code.
    I am very happy now. Your code is working :)
    Anonymous said...
    We've made an application allowing to upload file(s) from Android to any web server. It should work with your PHP script. See BucketUpload:
    Upload application for Android

    Anonymous said...
    i'm having a problem with paths here. where do u store ur files on ur phone?

    Shimul said...
    i think the file was saved in where the application resides
    Arnaud said...
    Does it work with a text file? Because I can't upload a simple xml file.
    Nothing is loaded on my server...really strange
    arnaud.farine AROBAS
    Shimul said...
    It was a code of long time ago, i am not familiar with current android sdk, so i am not sure if it will work
    Mudit Agarwal said...

    what is the size limit on the file you are uploading..coz i tried it for larger images and files and i am getting "OutOfMemory" Exception..

    PM me @
    siva said...
    i have copied the code to myapplication to upload the file for the android development,but it shows me a ERROR- can you fix and tel me how to use it..
    siva said...
    this code it stil shows me a ERROR can u tell me how to upload the files using the ANDROID ENVIRONMENT.

    richa said...
    This comment has been removed by the author.
    Andrew Sotzing said...
    Your post and sample code were extremely helpful to me. Have been slaving over this all night/day!

    Thanks much!
    Niklas said...
    not working at all.
    Jake Beasley said...
    Wow, saved me a lot of time!
    Umar said...
    could you please upload complete code here.

    actually i am getting following file path and getting file not found exception
    absolute path="/content:/media/external/images/media/2"

    could you please help me out why i am getting this?
    Umar said...
    This comment has been removed by the author.
    Umar said...
    This comment has been removed by the author.
    Umar said...
    how to add parameters in it its incomplete
    please post complete code.
    jana said...
    Thanks for the code!
    I tried uploading mp3 file
    i got java.lang.OutOfMemoryError.
    plz help me with this.
    Ian said...
    I'm wondering, can i send other information at the same time... i.e. $_POST['action'].... ???
    Dewr said...
    I'm wondering too, can you send other information at the same time... i.e. $_POST['action'].... ???
    Dewr said...
    Oh. I found a way to post other informations! urlString=urlString+"?key=value"+"&key2=value2"+"&key3=value3"+"&key4=value4"...;
    Dewr said...
    failed to send files. now I am referencing this trustful text ->
    Dewr said...
    urlString=urlString+"?key=value"+"&key2=value2"+"&key3=value3"+"&key4=value4"...; //this code will work well!
    Murali said...
    i have error in import org.apache.commons.codec.binary.Base64; and InterfaceHttpUtil ifPostBack; as 'cannot be resolved type'. and please help me. how to convert in android.
    murali-ma said...
    i have error in import org.apache.commons.codec.binary.Base64; and InterfaceHttpUtil ifPostBack; as 'cannot resolved type'. and please help how to convert it in android.
    pokershark103 said...
    Code is working, I tested it with php forms
    pokershark103 said...
    rajesh said...
    hey,thnx fr this 1 prob is code is working propery through wifi bt it's creating prob in GPRS .
    Tinker said...
    if i want to call a jsp code in place of php what will be the code can you provide it ... thanks in advance
    Ecommerce Web Developers said...
    I think most of the peoples are getting good knowledge about android. because your explanation is good and its the useful information, so thanks for providing this great knowledge.

    Android app developer
    Arvesh said...
    Thank you very much for that ! and u know what its because of people like u that am gonna start posting things to help others too !
    Glen Pinheiro said...
    interesting article, please check out my blog,
    swapslove15 said...
    i want ur xml file also to understand it,,,so pls send or copy pest ur whole xml code of this file pls,,,so i understand whats ur design
    Shiwani Malhotra said...
    Fahimshakir Freelancer Developer from Delhi-India,You can provide me part time work for Home,Part Time Developer/Freelancer For PHP , WordPress, Magento, Opencart, Shopify, Codeigniter, Website Maintenance in Delhi -india,
    Ankit Das said...
    Rohan said...
    Hi, I am trying to send an image that is shared from other app (say whatsapp) into server. I am getting the image as Uri type. how can i send this Uri of image to php server.?Please help. I am new to android.
    Rohan said...
    The image shared from other app is received by the function below.

    void handleSendImage(Intent intent) {
    Uri imageUri = (Uri) intent.getParcelableExtra(Intent.EXTRA_STREAM);

    I want to send image of this imageUri to phpserver from my android app.
    SAP Fiori said...
    I like very much..SAP Fiori
    Arayan Ghosh said...
    check this out: Kerala Lottery Result
    abhilash thakur said...
    please tell me the iphone 7 release date and ipad air 3
    tyler durden said...
    nice blog,, hope it will useful for everyone

    obat ampuh untuk kutil kelamin
    obat kutil kelamin salep dan kapsul
    Madam Enimem said...
    Arjuna Subagyo said...
    Nancy Maule said...
    Thank u so very much for posting such a wonderful Info.
    download cricket games | Power Cricket T20 Cup 2016 APK
    Rinku Dey said...
    Thanks for sharing the valuable info
    ps3 emulator | ps 3 emulator
    Tanu Chauhan said...
    Excellent post! I like this...Thanks for sharing!Java training jalandhar
    Shreya Mandal said...
    An excellent information provided thanks for all the information i must say great efforts made by you. Thanks a lot for all the information you provided.
    Watch Switzerland Vs Poland Live Streaming
    Rahul Bhatia said...
    Check out the One of best Free ringtones app - Myxer Free Ringtones.
    kanna said...
    iphone7 specifications and compare with other mobiles here........
    iphone 7s updates
    sushilkr said...
    sushilkr said...
    shailu said...
    katty said...
    Checkout the best iPhone ringtones maker app .
    katty said...
    find best free ringtones for android and iphone.
    Carlos Arango said...
    Excelente artículo. Me sirvió mucho.
    Wahub Akub said...
    Download Best Android App Store for downloading Android apps and games 9Apps APK
    Omkar Bhandare said...
    Ajay Kumar said...
    Free Ringtones are the most commonly used and best type of alert to get notified of a call or a message.
    prakash g said...
    prakash g said...
    TSAP updates said...
    TSAP updates said...
    <a href=">more info detail</a>
    Steev Rohleder said...
    Miriam Steve said...
    I always find this kind of blogs very interesting, something that makes me realize just how lucky i am to find them. It could be a great thing if i could find more of this, i can say that your post is of great help. You are of assistance to upcoming bloggers.
    Freelance Writers
    Albert Smith said...
    It yet another blog and it is bigger and better. The information posted has comprehensively covered the subject matter under discussion. I have learned a lot about the How to post file to a php server. I will be visiting this site occasionally as I Hire an Expert Writer to Rewrite my Case Study.
    Blogger said...
    Myxer Free Ringtones App Download, Best Sites to Download Free Ringtones: If you like to change your phone ringtone freely then you must myxer
    WiFi password hacker software

    Sujitkumar said...
    Nice info about Php it’s reallyhelpful…. If it possible share some more tutorials……….
    AYSK said...
    uktvnow has been one of the best apps to enjoy watching live tv in uk. i will recommend every to download UKTVNow app
    Charles V. Mounts said...
    Apple finally released iOS 11 beta download profile for iPhone and iPad developers. The iOS 11 update is available to download. There is no need to register an iOS UDID to run the latest firmware. Visit iOS Scoops to download iOS 11 beta.
    William Belton said...
    You can download vShare for mac right now on your device. vShare is filled with loads of new apps and games that can be downloaded free of cost.
    Bruce Doyle said...
    Everything you need to know about the Apple iOS 11, including impressions and analysis, photos, video, release date, prices, specs
    TSAP updates said...
    Great Blog!! That was amazing. Your thought processing is wonderful. The way you tell the thing is awesome.
    packers and movers lucknow
    packers and movers baroda
    rahul sharma said...
    IICE-Indore said...
    very interesting, good job and thanks for sharing such a good blog.
    Mobile App Development in Indore

    Packers and Movers said...
    venu puram said...
    Excellent Blog Post on How to post a file to a PHP Server. I really appreciate the full work done by you, As I am a PMP Certified I do a lot of research on these type of blogs and gain more knowledge, I made my Project Management Certification in Kuwait as I was been involved in handling various Projects from different countries I am able to understand your blog clearly

    Thank you so much, I hope to see more number of posts from you
    Harikumar ODMS said...
    Nice post
    Your post is just outstanding! thanks for such a post,its really going great work.
    local seo services in hyderabad
    venu puram said...
    Good Blog Post Keep Sharing such type of Information Very useful to all the main streams of accessing the ability
    PMP Training Certification in Kuwait
    Nazeer Rahaman said...
    Hi Nice Information Can you Further provide me updates on Servers related to PHP.
    Oracle SCM Course
    Oracle Financials Course
    Hadoop Admin Course
    Microsoft CRM Dynamics Course
    Lalita Chaple said...
    Thanks for sharing such great blog, it is useful for wordpress.
    Wordpress Expert in Pune
    Wordpress Freelance in Pune
    Linux Training India said... said...
    Hi thanks for your valuable information about php script. your post is great and outstanding it is very useful to me. please forward the further updates. Robotic Process Automation Coaching Centre in Hyderabad Kukatpally said...
    This comment has been removed by the author.
    Dileep Yadav said...
    Enter tracking number to track Speed post courier service, packet, cargo, parcel and get to know the delivery status online.
    Speed Post Tracking
    Dileep Yadav said...
    Hero Indian Super League, fondly known as Hero ISL all across the globe can be witnessed live on Hotstar. Watch ISL live streaming and catch the latest action live from the Hero Indian Super League 2016
    isl live streaming
    big bash Live Streaming
    Dileep Yadav said...
    The most entertaining T10 Cricket League 2017 is here. This league will be played in December this year and will see raining of sixes.
    T10 Cricket League Live Streaming
    Priyanka said...
    Hello sir how can solve path problem, I am trying a couple of more days but it could not resolve by police info
    Sonali Taral said...
    Awesome articles and i read your all blogs.
    Wordpress Expert in Pune
    Wordpress Freelancer in Pune
    Mary Petter said...
    Thanks for the post, I am techno savvy. I believe you hit the nail right on the head. I am highly impressed with your blog. It is very nicely explained. Your article adds best knowledge to our Java EE Training in Chennai. or learn thru Java EE Training in Chennai Students.
    Myra Dixit said...
    Thanks for the information. Very helpful blog for people who want know that Php Training in Ahmedabad, here I am sharing additional details of best Php courses in Ahmedabad just go with this Php classes in Ahmedabad

Post a Comment