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.

    Anonymous said...
    This comment has been removed by a blog administrator.
    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'].... ???
    Anonymous said...
    I'm wondering too, can you send other information at the same time... i.e. $_POST['action'].... ???
    Anonymous said...
    Oh. I found a way to post other informations! urlString=urlString+"?key=value"+"&key2=value2"+"&key3=value3"+"&key4=value4"...;
    Anonymous said...
    failed to send files. now I am referencing this trustful text ->
    Anonymous said...
    urlString=urlString+"?key=value"+"&key2=value2"+"&key3=value3"+"&key4=value4"...; //this code will work well!
    Anonymous 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.
    Anonymous 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
    Richard Swayar said...
    Australia Best Tutor is one of the best Online Assignment Help providers at an affordable price. Here All Learners or Students are getting best quality assignment help with reference and styles formatting.

    Visit us for more Information

    Australia Best Tutor
    Sydney, NSW, Australia
    Call @ +61-730-407-305
    Live Chat @

    Our Services

    Online assignment help
    my assignment help Student
    Assignment help Student
    help with assignment Student
    Students instant assignment help
    Students Assignment help Services
    Naresh K said...
    Appreciate Your Work, Very informative Blog on Android Development, I would like to share some information on Android Development training which will help for the blog here.
    Dileep Yadav said...
    Anonymous said...
    Phone Pedia said...
    Phone Pedia said...
    Thanks for the information
    Peter Johnson said...
    Awe! What An Blog Very Helpful and interesting Really A great center for acquiring knowledge.Very Helpful Post And Explained Very Clearly About All the things.Very Helpful. Coming To Our Self We Provide Restaurant Equipment Parts . Really Thankful For the blogger providing such a great information.Thank you. Have a Nice Day.
    seo said...
    This Blog Drives Me For Increasing my knowledge and to understand the basic concepts,really helpful and thankful we provide Urgent Care Services.Really Thanks For Posting Such an informative Article.I want to share this blog with my friends and family.
    Lathika Honey said...
    This Blog is very helpful and useful, came to know that I should be strong in my basics and this blog helps me to improve it, US Medical Residency in Chicago Services Provided by Us. Thanks For Posting.
    HoneyRoy said...
    I really enjoy to read your information about Iphone. Thanks for sharing Appreciate your work. I would like to share about online training. it will be helpful
    Lathika Honey said...
    Really Thanks For Posting Such a Useful and informative article. I would like to share this blog with my friends and Colleagues Tico Certification Training
    svr online Training said...
    Thanks For Sharing Such an Important and Useful Content On Mulesoft Certification Training
    Top 5 South Indian Packers said...
    AutoCAD training in Noida said...
    Each department of CAD have specific programmes which, while completed could provide you with a recognisable qualification that could assist you get a job in anything design enterprise which you would really like.

    AutoCAD training in Noida

    AutoCAD training institute in Noida

    Best AutoCAD training institute in Noida

    tushar rana said...
    6-week summer course in Noida - 6 weeks The summer course plays a crucial role in shaping the career of young aspiring / informatics students. This training has been specifically introduced so that students can become familiar with current industrial culture and industrial needs. Webtrackker technology offers a 6-month training program for students / graduates that includes small and large projects.
    6-week summer course in Noida
    Top 5 South Indian Packers said...
    Day i will be keep looking for any new updation in this website. Nice article
    Packers movers Trichy
    Packers movers Tirupur
    Packers movers Salem
    raman rajput said...
    raman rajput said...
    raman rajput said...
    raman rajput said...
    raman rajput said...
    raman rajput said...
    24Layouts said...
    Thanks For Sharing Such an Useful Information....

    Vizag Real Estate
    Rohan kumar said...
    Cloud Computing Training In Noida
    Webtrackker is IT based company in many countries. Webtrackker will provide you a real time projects based training on Cloud Computing. If you are looking for the Cloud computing training in Noida then you can join the webtrackker technology.
    Cloud Computing Training In Noida , Cloud Computing Training center In Noida , Cloud Computing Training institute In Noida ,

    Company Address:
    Webtrackker Technology
    C- 67, Sector- 63, Noida
    prem said...
    Video editing course in Noida
    Video editing training institute in Noida- Webtrackker Technology is and IT Training institute providing the Video editing course in Noida, FCP, Final Cut Pro Training in Noida. For more call us- 8802820025.
    Video editing course in Noida
    best video editig course in noida
    best video edtitng institute in noida
    Company Address:
    Webtrackker Technology
    C- 67, Sector- 63, Noida
    Phone: 01204330760, 8802820025
    bhadra said...
    I Just Love to read Your Articles Because they are very easy to understand.Very Helpful Post And Explained Very Clearly About All the things.Very Helpful.... Web Development Services
    nancy said...
    This is a 2 good post. This post gives truly quality information.

    RPA Training in Hyderabad
    amarraj paindit said...
    amarraj paindit said...
    nancy said...
    It's very nice blog. I'm so happy to gain some knowledge from here.

    MSBI Training in Hyderabad

    Bee Yes said...
    Amazing Article ! I have bookmarked this article page as i received good information from this. All the best for the upcoming articles. I will be waiting for your new articles. Thank You ! Kindly Visit Us @ coimbatore airport taxi | Ooty travels
    Neelima said...
    interesting blog, here a lot of valuable information is available, it is very useful information. we offer this Android online and classroom training at low caste and with real-time trainers. please visit our site for more details Android training
    Arvind Rawat said...

    Like different elements of India, numerous oil and spices usually cross into making food. This effects in substances getting caught to the partitions of the filter out.
    Visit here
    Best kitchen chimney installation and service
    Auto clean chimney sevice in Faridabad
    kiran mai said...
    vimal chauhan said...
    Best tutorial i have ever seen on how to post a PHP file. Great work man.
    Microsoft Dynamic CRM.
    kiran mai said...
    I am very happy after find this post. Thanks for sharing this Informative content. Well explained. Got to learn new things from your Blog.

    Tekslate Online Trainings.

    Robotic Process Automation Tutorial said...
    Really great work. Your article was very helpful.Thanks for sharing valuable points.Keep sharing.Thank You
    rpa training in chennai | rpa training in velachery | trending technologies list 2018

    Unknown said...
    I have gone through the post and I must admit that I like it. Keep doing the great work. I will definitely have to bookmark this page for future reference. I will also refer my friends to come and have the same experience as I did. Thanks so much. Anyone looking for Research papers help check out our Sample Essays and the assignments we have done before
    Aman CSE said...
    Such a wondrful post on Blueprism .This post really helps the students who want to gain knowledge of Blueprism .Thank you sharing such a wonderful post on Blueprism .
    Thanks and Regards,
    blue prism training institute in chennai
    uipath training in chennai
    best blue prism training in chennai
    Eminent It Info said...
    ProPlus Academy said...
    Hey Nice Blog!! Thanks For Sharing!!!Wonderful blog & good post.Its really helpful for me, waiting for a more new post. Keep Blogging!
    php course
    Web development
    Twinkle said...
    UniversalTelecoms said...
    Very Nice Article to read. Blog articles helped me alot in many ways to find the good solution. Am very happy to comments here. Thanks for sharing this kind of wonderful article in this blog. Lovely ! CCTV Camera Supplier | MATRIX dealers
    Splendid Interiors said...
    Ah,so beautiful and wonderful post!An opportunity to read a fantastic and imaginary blogs.It gives me lots of pleasure and interest.Thanks for sharing.
    Find the Interior Designers in Vijayawada
    Katherine tk said...
    Great informative post. I really appreciate your work. keep sharing the information.


Post a Comment